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::atomic::{AtomicU32, Ordering};
18use std::sync::Arc;
19use std::time::Duration;
20
21use ::auth::{Identity, 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_query::Output;
27use common_telemetry::{debug, error, tracing, warn};
28use datafusion_common::ParamValues;
29use datafusion_expr::LogicalPlan;
30use datatypes::prelude::ConcreteDataType;
31use itertools::Itertools;
32use opensrv_mysql::{
33    AsyncMysqlShim, Column, ErrorKind, InitWriter, ParamParser, ParamValue, QueryResultWriter,
34    StatementMetaWriter, ValueInner,
35};
36use parking_lot::RwLock;
37use query::query_engine::DescribeResult;
38use rand::RngCore;
39use session::context::{Channel, QueryContextRef};
40use session::{Session, SessionRef};
41use snafu::{ensure, ResultExt};
42use sql::dialect::MySqlDialect;
43use sql::parser::{ParseOptions, ParserContext};
44use sql::statements::statement::Statement;
45use tokio::io::AsyncWrite;
46
47use crate::error::{self, DataFrameSnafu, InvalidPrepareStatementSnafu, Result};
48use crate::metrics::METRIC_AUTH_FAILURE;
49use crate::mysql::helper::{
50    self, fix_placeholder_types, format_placeholder, replace_placeholders, transform_placeholders,
51};
52use crate::mysql::writer;
53use crate::mysql::writer::{create_mysql_column, handle_err};
54use crate::query_handler::sql::ServerSqlQueryHandlerRef;
55use crate::SqlPlan;
56
57const MYSQL_NATIVE_PASSWORD: &str = "mysql_native_password";
58const MYSQL_CLEAR_PASSWORD: &str = "mysql_clear_password";
59
60/// Parameters for the prepared statement
61enum Params<'a> {
62    /// Parameters passed through protocol
63    ProtocolParams(Vec<ParamValue<'a>>),
64    /// Parameters passed through cli
65    CliParams(Vec<sql::ast::Expr>),
66}
67
68impl Params<'_> {
69    fn len(&self) -> usize {
70        match self {
71            Params::ProtocolParams(params) => params.len(),
72            Params::CliParams(params) => params.len(),
73        }
74    }
75}
76
77// An intermediate shim for executing MySQL queries.
78pub struct MysqlInstanceShim {
79    query_handler: ServerSqlQueryHandlerRef,
80    salt: [u8; 20],
81    session: SessionRef,
82    user_provider: Option<UserProviderRef>,
83    prepared_stmts: Arc<RwLock<HashMap<String, SqlPlan>>>,
84    prepared_stmts_counter: AtomicU32,
85    process_id: u32,
86    prepared_stmt_cache_size: usize,
87}
88
89impl MysqlInstanceShim {
90    pub fn create(
91        query_handler: ServerSqlQueryHandlerRef,
92        user_provider: Option<UserProviderRef>,
93        client_addr: SocketAddr,
94        process_id: u32,
95        prepared_stmt_cache_size: usize,
96    ) -> MysqlInstanceShim {
97        // init a random salt
98        let mut bs = vec![0u8; 20];
99        let mut rng = rand::rng();
100        rng.fill_bytes(bs.as_mut());
101
102        let mut scramble: [u8; 20] = [0; 20];
103        for i in 0..20 {
104            scramble[i] = bs[i] & 0x7fu8;
105            if scramble[i] == b'\0' || scramble[i] == b'$' {
106                scramble[i] += 1;
107            }
108        }
109
110        MysqlInstanceShim {
111            query_handler,
112            salt: scramble,
113            session: Arc::new(Session::new(
114                Some(client_addr),
115                Channel::Mysql,
116                Default::default(),
117                process_id,
118            )),
119            user_provider,
120            prepared_stmts: Default::default(),
121            prepared_stmts_counter: AtomicU32::new(1),
122            process_id,
123            prepared_stmt_cache_size,
124        }
125    }
126
127    #[tracing::instrument(skip_all, name = "mysql::do_query")]
128    async fn do_query(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
129        if let Some(output) =
130            crate::mysql::federated::check(query, query_ctx.clone(), self.session.clone())
131        {
132            vec![Ok(output)]
133        } else {
134            self.query_handler.do_query(query, query_ctx.clone()).await
135        }
136    }
137
138    /// Execute the logical plan and return the output
139    async fn do_exec_plan(
140        &self,
141        query: &str,
142        stmt: Option<Statement>,
143        plan: LogicalPlan,
144        query_ctx: QueryContextRef,
145    ) -> Result<Output> {
146        if let Some(output) =
147            crate::mysql::federated::check(query, query_ctx.clone(), self.session.clone())
148        {
149            Ok(output)
150        } else {
151            self.query_handler.do_exec_plan(stmt, plan, query_ctx).await
152        }
153    }
154
155    /// Describe the statement
156    async fn do_describe(
157        &self,
158        statement: Statement,
159        query_ctx: QueryContextRef,
160    ) -> Result<Option<DescribeResult>> {
161        self.query_handler.do_describe(statement, query_ctx).await
162    }
163
164    /// Save query and logical plan with a given statement key
165    fn save_plan(&self, plan: SqlPlan, stmt_key: String) -> Result<()> {
166        let mut prepared_stmts = self.prepared_stmts.write();
167        let max_capacity = self.prepared_stmt_cache_size;
168
169        let is_update = prepared_stmts.contains_key(&stmt_key);
170
171        if !is_update && prepared_stmts.len() >= max_capacity {
172            return error::InternalSnafu {
173                err_msg: format!(
174                    "Prepared statement cache is full, max capacity: {}",
175                    max_capacity
176                ),
177            }
178            .fail();
179        }
180
181        let _ = prepared_stmts.insert(stmt_key, plan);
182        Ok(())
183    }
184
185    /// Retrieve the query and logical plan by a given statement key
186    fn plan(&self, stmt_key: &str) -> Option<SqlPlan> {
187        let guard = self.prepared_stmts.read();
188        guard.get(stmt_key).cloned()
189    }
190
191    /// Save the prepared statement and return the parameters and result columns
192    async fn do_prepare(
193        &mut self,
194        raw_query: &str,
195        query_ctx: QueryContextRef,
196        stmt_key: String,
197    ) -> Result<(Vec<Column>, Vec<Column>)> {
198        let (query, param_num) = replace_placeholders(raw_query);
199
200        let statement = validate_query(raw_query).await?;
201
202        // We have to transform the placeholder, because DataFusion only parses placeholders
203        // in the form of "$i", it can't process "?" right now.
204        let statement = transform_placeholders(statement);
205
206        let describe_result = self
207            .do_describe(statement.clone(), query_ctx.clone())
208            .await?;
209        let (mut plan, schema) = if let Some(DescribeResult {
210            logical_plan,
211            schema,
212        }) = describe_result
213        {
214            (Some(logical_plan), Some(schema))
215        } else {
216            (None, None)
217        };
218
219        let params = if let Some(plan) = &mut plan {
220            fix_placeholder_types(plan)?;
221            debug!("Plan after fix placeholder types: {:#?}", plan);
222            prepared_params(
223                &plan
224                    .get_parameter_types()
225                    .context(DataFrameSnafu)?
226                    .into_iter()
227                    .map(|(k, v)| (k, v.map(|v| ConcreteDataType::from_arrow_type(&v))))
228                    .collect(),
229            )?
230        } else {
231            dummy_params(param_num)?
232        };
233
234        let columns = schema
235            .as_ref()
236            .map(|schema| {
237                schema
238                    .column_schemas()
239                    .iter()
240                    .map(|column_schema| {
241                        create_mysql_column(&column_schema.data_type, &column_schema.name)
242                    })
243                    .collect::<Result<Vec<_>>>()
244            })
245            .transpose()?
246            .unwrap_or_default();
247
248        // DataFusion may optimize the plan so that some parameters are not used.
249        if params.len() != param_num - 1 {
250            self.save_plan(
251                SqlPlan {
252                    query: query.to_string(),
253                    statement: Some(statement),
254                    plan: None,
255                    schema: None,
256                },
257                stmt_key,
258            )
259            .map_err(|e| {
260                error!(e; "Failed to save prepared statement");
261                e
262            })?;
263        } else {
264            self.save_plan(
265                SqlPlan {
266                    query: query.to_string(),
267                    statement: Some(statement),
268                    plan,
269                    schema,
270                },
271                stmt_key,
272            )
273            .map_err(|e| {
274                error!(e; "Failed to save prepared statement");
275                e
276            })?;
277        }
278
279        Ok((params, columns))
280    }
281
282    async fn do_execute(
283        &mut self,
284        query_ctx: QueryContextRef,
285        stmt_key: String,
286        params: Params<'_>,
287    ) -> Result<Vec<std::result::Result<Output, error::Error>>> {
288        let sql_plan = match self.plan(&stmt_key) {
289            None => {
290                return error::PrepareStatementNotFoundSnafu { name: stmt_key }.fail();
291            }
292            Some(sql_plan) => sql_plan,
293        };
294
295        let outputs = match sql_plan.plan {
296            Some(mut plan) => {
297                fix_placeholder_types(&mut plan)?;
298                let param_types = plan
299                    .get_parameter_types()
300                    .context(DataFrameSnafu)?
301                    .into_iter()
302                    .map(|(k, v)| (k, v.map(|v| ConcreteDataType::from_arrow_type(&v))))
303                    .collect::<HashMap<_, _>>();
304
305                if params.len() != param_types.len() {
306                    return error::InternalSnafu {
307                        err_msg: "Prepare statement params number mismatch".to_string(),
308                    }
309                    .fail();
310                }
311
312                let plan = match params {
313                    Params::ProtocolParams(params) => {
314                        replace_params_with_values(&plan, param_types, &params)
315                    }
316                    Params::CliParams(params) => {
317                        replace_params_with_exprs(&plan, param_types, &params)
318                    }
319                }?;
320
321                debug!("Mysql execute prepared plan: {}", plan.display_indent());
322                vec![
323                    self.do_exec_plan(
324                        &sql_plan.query,
325                        sql_plan.statement.clone(),
326                        plan,
327                        query_ctx.clone(),
328                    )
329                    .await,
330                ]
331            }
332            None => {
333                let param_strs = match params {
334                    Params::ProtocolParams(params) => {
335                        params.iter().map(convert_param_value_to_string).collect()
336                    }
337                    Params::CliParams(params) => params.iter().map(|x| x.to_string()).collect(),
338                };
339                debug!(
340                    "do_execute Replacing with Params: {:?}, Original Query: {}",
341                    param_strs, sql_plan.query
342                );
343                let query = replace_params(param_strs, sql_plan.query);
344                debug!("Mysql execute replaced query: {}", query);
345                self.do_query(&query, query_ctx.clone()).await
346            }
347        };
348
349        Ok(outputs)
350    }
351
352    /// Remove the prepared statement by a given statement key
353    fn do_close(&mut self, stmt_key: String) {
354        let mut guard = self.prepared_stmts.write();
355        let _ = guard.remove(&stmt_key);
356    }
357
358    fn auth_plugin(&self) -> &str {
359        if self
360            .user_provider
361            .as_ref()
362            .map(|x| x.external())
363            .unwrap_or(false)
364        {
365            MYSQL_CLEAR_PASSWORD
366        } else {
367            MYSQL_NATIVE_PASSWORD
368        }
369    }
370}
371
372#[async_trait]
373impl<W: AsyncWrite + Send + Sync + Unpin> AsyncMysqlShim<W> for MysqlInstanceShim {
374    type Error = error::Error;
375
376    fn version(&self) -> String {
377        std::env::var("GREPTIMEDB_MYSQL_SERVER_VERSION").unwrap_or_else(|_| "8.4.2".to_string())
378    }
379
380    fn connect_id(&self) -> u32 {
381        self.process_id
382    }
383
384    fn default_auth_plugin(&self) -> &str {
385        self.auth_plugin()
386    }
387
388    async fn auth_plugin_for_username<'a, 'user>(&'a self, _user: &'user [u8]) -> &'a str {
389        self.auth_plugin()
390    }
391
392    fn salt(&self) -> [u8; 20] {
393        self.salt
394    }
395
396    async fn authenticate(
397        &self,
398        auth_plugin: &str,
399        username: &[u8],
400        salt: &[u8],
401        auth_data: &[u8],
402    ) -> bool {
403        // if not specified then **greptime** will be used
404        let username = String::from_utf8_lossy(username);
405
406        let mut user_info = None;
407        let addr = self
408            .session
409            .conn_info()
410            .client_addr
411            .map(|addr| addr.to_string());
412        if let Some(user_provider) = &self.user_provider {
413            let user_id = Identity::UserId(&username, addr.as_deref());
414
415            let password = match auth_plugin {
416                MYSQL_NATIVE_PASSWORD => Password::MysqlNativePassword(auth_data, salt),
417                MYSQL_CLEAR_PASSWORD => {
418                    // The raw bytes received could be represented in C-like string, ended in '\0'.
419                    // We must "trim" it to get the real password string.
420                    let password = if let &[password @ .., 0] = &auth_data {
421                        password
422                    } else {
423                        auth_data
424                    };
425                    Password::PlainText(String::from_utf8_lossy(password).to_string().into())
426                }
427                other => {
428                    error!("Unsupported mysql auth plugin: {}", other);
429                    return false;
430                }
431            };
432            match user_provider.authenticate(user_id, password).await {
433                Ok(userinfo) => {
434                    user_info = Some(userinfo);
435                }
436                Err(e) => {
437                    METRIC_AUTH_FAILURE
438                        .with_label_values(&[e.status_code().as_ref()])
439                        .inc();
440                    warn!(e; "Failed to auth");
441                    return false;
442                }
443            };
444        }
445        let user_info =
446            user_info.unwrap_or_else(|| auth::userinfo_by_name(Some(username.to_string())));
447
448        self.session.set_user_info(user_info);
449
450        true
451    }
452
453    async fn on_prepare<'a>(
454        &'a mut self,
455        raw_query: &'a str,
456        w: StatementMetaWriter<'a, W>,
457    ) -> Result<()> {
458        let query_ctx = self.session.new_query_context();
459        let stmt_id = self.prepared_stmts_counter.fetch_add(1, Ordering::Relaxed);
460        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
461        let (params, columns) = self
462            .do_prepare(raw_query, query_ctx.clone(), stmt_key)
463            .await?;
464        debug!("on_prepare: Params: {:?}, Columns: {:?}", params, columns);
465        w.reply(stmt_id, &params, &columns).await?;
466        crate::metrics::METRIC_MYSQL_PREPARED_COUNT
467            .with_label_values(&[query_ctx.get_db_string().as_str()])
468            .inc();
469        return Ok(());
470    }
471
472    async fn on_execute<'a>(
473        &'a mut self,
474        stmt_id: u32,
475        p: ParamParser<'a>,
476        w: QueryResultWriter<'a, W>,
477    ) -> Result<()> {
478        let query_ctx = self.session.new_query_context();
479        let db = query_ctx.get_db_string();
480        let _timer = crate::metrics::METRIC_MYSQL_QUERY_TIMER
481            .with_label_values(&[crate::metrics::METRIC_MYSQL_BINQUERY, db.as_str()])
482            .start_timer();
483
484        let params: Vec<ParamValue> = p.into_iter().collect();
485        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
486
487        let outputs = match self
488            .do_execute(query_ctx.clone(), stmt_key, Params::ProtocolParams(params))
489            .await
490        {
491            Ok(outputs) => outputs,
492            Err(e) => {
493                let (kind, err) = handle_err(e, query_ctx);
494                debug!(
495                    "Failed to execute prepared statement, kind: {:?}, err: {}",
496                    kind, err
497                );
498                w.error(kind, err.as_bytes()).await?;
499                return Ok(());
500            }
501        };
502
503        writer::write_output(w, query_ctx, outputs).await?;
504
505        Ok(())
506    }
507
508    async fn on_close<'a>(&'a mut self, stmt_id: u32)
509    where
510        W: 'async_trait,
511    {
512        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
513        self.do_close(stmt_key);
514    }
515
516    #[tracing::instrument(skip_all, fields(protocol = "mysql"))]
517    async fn on_query<'a>(
518        &'a mut self,
519        query: &'a str,
520        writer: QueryResultWriter<'a, W>,
521    ) -> Result<()> {
522        let query_ctx = self.session.new_query_context();
523        let db = query_ctx.get_db_string();
524        let _timer = crate::metrics::METRIC_MYSQL_QUERY_TIMER
525            .with_label_values(&[crate::metrics::METRIC_MYSQL_TEXTQUERY, db.as_str()])
526            .start_timer();
527
528        let query_upcase = query.to_uppercase();
529        if query_upcase.starts_with("PREPARE ") {
530            match ParserContext::parse_mysql_prepare_stmt(query, query_ctx.sql_dialect()) {
531                Ok((stmt_name, stmt)) => {
532                    let prepare_results =
533                        self.do_prepare(&stmt, query_ctx.clone(), stmt_name).await;
534                    match prepare_results {
535                        Ok(_) => {
536                            let outputs = vec![Ok(Output::new_with_affected_rows(0))];
537                            writer::write_output(writer, query_ctx, outputs).await?;
538                            return Ok(());
539                        }
540                        Err(e) => {
541                            writer
542                                .error(ErrorKind::ER_SP_BADSTATEMENT, e.output_msg().as_bytes())
543                                .await?;
544                            return Ok(());
545                        }
546                    }
547                }
548                Err(e) => {
549                    writer
550                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
551                        .await?;
552                    return Ok(());
553                }
554            }
555        } else if query_upcase.starts_with("EXECUTE ") {
556            match ParserContext::parse_mysql_execute_stmt(query, query_ctx.sql_dialect()) {
557                Ok((stmt_name, params)) => {
558                    let outputs = match self
559                        .do_execute(query_ctx.clone(), stmt_name, Params::CliParams(params))
560                        .await
561                    {
562                        Ok(outputs) => outputs,
563                        Err(e) => {
564                            let (kind, err) = handle_err(e, query_ctx);
565                            debug!(
566                                "Failed to execute prepared statement, kind: {:?}, err: {}",
567                                kind, err
568                            );
569                            writer.error(kind, err.as_bytes()).await?;
570                            return Ok(());
571                        }
572                    };
573                    writer::write_output(writer, query_ctx, outputs).await?;
574                    return Ok(());
575                }
576                Err(e) => {
577                    writer
578                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
579                        .await?;
580                    return Ok(());
581                }
582            }
583        } else if query_upcase.starts_with("DEALLOCATE ") {
584            match ParserContext::parse_mysql_deallocate_stmt(query, query_ctx.sql_dialect()) {
585                Ok(stmt_name) => {
586                    self.do_close(stmt_name);
587                    let outputs = vec![Ok(Output::new_with_affected_rows(0))];
588                    writer::write_output(writer, query_ctx, outputs).await?;
589                    return Ok(());
590                }
591                Err(e) => {
592                    writer
593                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
594                        .await?;
595                    return Ok(());
596                }
597            }
598        }
599
600        let outputs = self.do_query(query, query_ctx.clone()).await;
601        writer::write_output(writer, query_ctx, outputs).await?;
602        Ok(())
603    }
604
605    async fn on_init<'a>(&'a mut self, database: &'a str, w: InitWriter<'a, W>) -> Result<()> {
606        let (catalog_from_db, schema) = parse_optional_catalog_and_schema_from_db_string(database);
607        let catalog = if let Some(catalog) = &catalog_from_db {
608            catalog.to_string()
609        } else {
610            self.session.catalog()
611        };
612
613        if !self
614            .query_handler
615            .is_valid_schema(&catalog, &schema)
616            .await?
617        {
618            return w
619                .error(
620                    ErrorKind::ER_WRONG_DB_NAME,
621                    format!("Unknown database '{}'", database).as_bytes(),
622                )
623                .await
624                .map_err(|e| e.into());
625        }
626
627        let user_info = &self.session.user_info();
628
629        if let Some(schema_validator) = &self.user_provider {
630            if let Err(e) = schema_validator
631                .authorize(&catalog, &schema, user_info)
632                .await
633            {
634                METRIC_AUTH_FAILURE
635                    .with_label_values(&[e.status_code().as_ref()])
636                    .inc();
637                return w
638                    .error(
639                        ErrorKind::ER_DBACCESS_DENIED_ERROR,
640                        e.output_msg().as_bytes(),
641                    )
642                    .await
643                    .map_err(|e| e.into());
644            }
645        }
646
647        if catalog_from_db.is_some() {
648            self.session.set_catalog(catalog)
649        }
650        self.session.set_schema(schema);
651
652        w.ok().await.map_err(|e| e.into())
653    }
654}
655
656fn convert_param_value_to_string(param: &ParamValue) -> String {
657    match param.value.into_inner() {
658        ValueInner::Int(u) => u.to_string(),
659        ValueInner::UInt(u) => u.to_string(),
660        ValueInner::Double(u) => u.to_string(),
661        ValueInner::NULL => "NULL".to_string(),
662        ValueInner::Bytes(b) => format!("'{}'", &String::from_utf8_lossy(b)),
663        ValueInner::Date(_) => format!("'{}'", NaiveDate::from(param.value)),
664        ValueInner::Datetime(_) => format!("'{}'", NaiveDateTime::from(param.value)),
665        ValueInner::Time(_) => format_duration(Duration::from(param.value)),
666    }
667}
668
669fn replace_params(params: Vec<String>, query: String) -> String {
670    let mut query = query;
671    let mut index = 1;
672    for param in params {
673        query = query.replace(&format_placeholder(index), &param);
674        index += 1;
675    }
676    query
677}
678
679fn format_duration(duration: Duration) -> String {
680    let seconds = duration.as_secs() % 60;
681    let minutes = (duration.as_secs() / 60) % 60;
682    let hours = (duration.as_secs() / 60) / 60;
683    format!("'{}:{}:{}'", hours, minutes, seconds)
684}
685
686fn replace_params_with_values(
687    plan: &LogicalPlan,
688    param_types: HashMap<String, Option<ConcreteDataType>>,
689    params: &[ParamValue],
690) -> Result<LogicalPlan> {
691    debug_assert_eq!(param_types.len(), params.len());
692
693    debug!(
694        "replace_params_with_values(param_types: {:#?}, params: {:#?}, plan: {:#?})",
695        param_types,
696        params
697            .iter()
698            .map(|x| format!("({:?}, {:?})", x.value, x.coltype))
699            .join(", "),
700        plan
701    );
702
703    let mut values = Vec::with_capacity(params.len());
704
705    for (i, param) in params.iter().enumerate() {
706        if let Some(Some(t)) = param_types.get(&format_placeholder(i + 1)) {
707            let value = helper::convert_value(param, t)?;
708
709            values.push(value);
710        }
711    }
712
713    plan.clone()
714        .replace_params_with_values(&ParamValues::List(values.clone()))
715        .context(DataFrameSnafu)
716}
717
718fn replace_params_with_exprs(
719    plan: &LogicalPlan,
720    param_types: HashMap<String, Option<ConcreteDataType>>,
721    params: &[sql::ast::Expr],
722) -> Result<LogicalPlan> {
723    debug_assert_eq!(param_types.len(), params.len());
724
725    debug!(
726        "replace_params_with_exprs(param_types: {:#?}, params: {:#?}, plan: {:#?})",
727        param_types,
728        params.iter().map(|x| format!("({:?})", x)).join(", "),
729        plan
730    );
731
732    let mut values = Vec::with_capacity(params.len());
733
734    for (i, param) in params.iter().enumerate() {
735        if let Some(Some(t)) = param_types.get(&format_placeholder(i + 1)) {
736            let value = helper::convert_expr_to_scalar_value(param, t)?;
737
738            values.push(value);
739        }
740    }
741
742    plan.clone()
743        .replace_params_with_values(&ParamValues::List(values.clone()))
744        .context(DataFrameSnafu)
745}
746
747async fn validate_query(query: &str) -> Result<Statement> {
748    let statement =
749        ParserContext::create_with_dialect(query, &MySqlDialect {}, ParseOptions::default());
750    let mut statement = statement.map_err(|e| {
751        InvalidPrepareStatementSnafu {
752            err_msg: e.output_msg(),
753        }
754        .build()
755    })?;
756
757    ensure!(
758        statement.len() == 1,
759        InvalidPrepareStatementSnafu {
760            err_msg: "prepare statement only support single statement".to_string(),
761        }
762    );
763
764    let statement = statement.remove(0);
765
766    Ok(statement)
767}
768
769fn dummy_params(index: usize) -> Result<Vec<Column>> {
770    let mut params = Vec::with_capacity(index - 1);
771
772    for _ in 1..index {
773        params.push(create_mysql_column(&ConcreteDataType::null_datatype(), "")?);
774    }
775
776    Ok(params)
777}
778
779/// Parameters that the client must provide when executing the prepared statement.
780fn prepared_params(param_types: &HashMap<String, Option<ConcreteDataType>>) -> Result<Vec<Column>> {
781    let mut params = Vec::with_capacity(param_types.len());
782
783    // Placeholder index starts from 1
784    for index in 1..=param_types.len() {
785        if let Some(Some(t)) = param_types.get(&format_placeholder(index)) {
786            let column = create_mysql_column(t, "")?;
787            params.push(column);
788        }
789    }
790
791    Ok(params)
792}