Skip to main content

toasty_driver_mysql/
lib.rs

1#![warn(missing_docs)]
2#![allow(clippy::needless_range_loop)]
3
4//! Toasty drivers for [MySQL](https://www.mysql.com/) and
5//! [MariaDB](https://mariadb.org/) 11.8 and later, using [SQLx](https://docs.rs/sqlx).
6//!
7//! # Examples
8//!
9//! ```no_run
10//! use toasty_driver_mysql::{MySQL, MariaDB};
11//!
12//! let driver = MySQL::new("mysql://localhost/mydb").unwrap();
13//! let driver = MariaDB::new("mariadb://localhost/mydb").unwrap();
14//! ```
15
16mod mariadb;
17pub use mariadb::MariaDB;
18
19mod value;
20pub(crate) use value::Value;
21
22use async_trait::async_trait;
23use sqlx::mysql::{MySqlArguments, MySqlConnectOptions, MySqlConnection, MySqlDatabaseError};
24use sqlx::{AssertSqlSafe, ConnectOptions as _, Connection as SqlxConnection, Row};
25use std::{borrow::Cow, cell::Cell, sync::Arc};
26use toasty_core::{
27    Result, Schema,
28    driver::{
29        Capability, ConnectContext, ConnectionUrl, Dialect, Driver, ExecResponse, Operation,
30        QueryLogConfig,
31        log::QueryLog,
32        operation::{RawSqlRet, Transaction, TransactionMode},
33    },
34    schema::db::{self, Table},
35    stmt::{self, ValueRecord},
36};
37use toasty_sql::{self as sql};
38
39enum SqlReturn {
40    Count,
41    LastInsertId(stmt::Type),
42    Infer,
43    Types(Vec<stmt::Type>),
44}
45
46/// Classifies a SQLx MySQL error into a Toasty error.
47///
48/// Transport and protocol failures become `ConnectionLost`. MySQL
49/// errors with numbers that Toasty understands become typed errors.
50/// Everything else becomes `DriverOperationFailed`.
51fn classify_mysql_error(e: sqlx::Error) -> toasty_core::Error {
52    match e {
53        error @ (sqlx::Error::Io(_) | sqlx::Error::Protocol(_) | sqlx::Error::WorkerCrashed) => {
54            toasty_core::Error::connection_lost(error)
55        }
56        sqlx::Error::Database(database_error) => {
57            let mysql_error = database_error
58                .try_downcast_ref::<MySqlDatabaseError>()
59                .expect("SQLx returned a non-MySQL database error from a MySQL connection");
60            let number = mysql_error.number();
61            let message = mysql_error.message().to_owned();
62
63            match number {
64                1213 => toasty_core::Error::serialization_failure(message),
65                1792 => toasty_core::Error::read_only_transaction(message),
66                _ => toasty_core::Error::driver_operation_failed(sqlx::Error::Database(
67                    database_error,
68                )),
69            }
70        }
71        other => toasty_core::Error::driver_operation_failed(other),
72    }
73}
74
75/// Classifies a SQLx error and records whether the connection is still usable.
76fn record_mysql_err(valid: &Cell<bool>, e: sqlx::Error) -> toasty_core::Error {
77    let err = classify_mysql_error(e);
78    if err.is_connection_lost() {
79        valid.set(false);
80    }
81    err
82}
83
84/// A MySQL [`Driver`] that connects through SQLx.
85///
86/// # Examples
87///
88/// ```no_run
89/// use toasty_driver_mysql::MySQL;
90///
91/// let driver = MySQL::new("mysql://localhost/mydb").unwrap();
92/// ```
93#[derive(Debug)]
94pub struct MySQL {
95    url: String,
96    opts: MySqlConnectOptions,
97    capability: &'static Capability,
98}
99
100impl MySQL {
101    /// Creates a MySQL driver from a SQLx connection URL.
102    ///
103    /// The URL must use the `mysql` scheme and include a database path, such as
104    /// `mysql://user:pass@host:3306/dbname`.
105    pub fn new(url: impl Into<String>) -> Result<Self> {
106        Self::with_capability(url, "mysql", &Capability::MYSQL)
107    }
108
109    fn with_capability(
110        url: impl Into<String>,
111        scheme: &str,
112        capability: &'static Capability,
113    ) -> Result<Self> {
114        let url_str = url.into();
115        let url = ConnectionUrl::parse(&url_str)?;
116
117        if !url.has_scheme(scheme) {
118            return Err(toasty_core::Error::invalid_connection_url(format!(
119                "connection url does not have a `{scheme}` scheme; url={}",
120                url.as_str()
121            )));
122        }
123
124        url.host()?.ok_or_else(|| {
125            toasty_core::Error::invalid_connection_url(format!(
126                "missing host in connection URL; url={}",
127                url.as_str()
128            ))
129        })?;
130
131        if url.path().is_empty() {
132            return Err(toasty_core::Error::invalid_connection_url(format!(
133                "no database specified - missing path in connection URL; url={}",
134                url.as_str()
135            )));
136        }
137
138        let opts = url
139            .as_str()
140            .parse::<MySqlConnectOptions>()
141            .map_err(toasty_core::Error::driver_operation_failed)?
142            .disable_statement_logging();
143
144        Ok(Self {
145            url: url_str,
146            opts,
147            capability,
148        })
149    }
150}
151
152/// The serializer for the dialect `capability` names.
153fn serializer<'a>(capability: &Capability, schema: &'a db::Schema) -> sql::Serializer<'a> {
154    match capability.sql {
155        Some(Dialect::MariaDb) => sql::Serializer::mariadb(schema),
156        _ => sql::Serializer::mysql(schema),
157    }
158}
159
160#[async_trait]
161impl Driver for MySQL {
162    fn url(&self) -> Cow<'_, str> {
163        Cow::Borrowed(&self.url)
164    }
165
166    fn capability(&self) -> &'static Capability {
167        self.capability
168    }
169
170    async fn connect(
171        &self,
172        cx: &ConnectContext,
173    ) -> Result<Box<dyn toasty_core::driver::Connection>> {
174        let conn = MySqlConnection::connect_with(&self.opts)
175            .await
176            .map_err(classify_mysql_error)?;
177        let mut connection = Connection::with_capability(conn, self.capability);
178        connection.query_log = cx.query_log;
179        Ok(Box::new(connection))
180    }
181
182    async fn reset_db(&self) -> Result<()> {
183        let mut conn = MySqlConnection::connect_with(&self.opts)
184            .await
185            .map_err(classify_mysql_error)?;
186        let dbname = self.opts.get_database().ok_or_else(|| {
187            toasty_core::Error::invalid_connection_url("no database name configured")
188        })?;
189
190        let dbname = format!("`{}`", dbname.replace('`', "``"));
191
192        sqlx::raw_sql(AssertSqlSafe(format!("DROP DATABASE IF EXISTS {dbname}")))
193            .execute(&mut conn)
194            .await
195            .map_err(classify_mysql_error)?;
196        sqlx::raw_sql(AssertSqlSafe(format!("CREATE DATABASE {dbname}")))
197            .execute(&mut conn)
198            .await
199            .map_err(classify_mysql_error)?;
200        sqlx::raw_sql(AssertSqlSafe(format!("USE {dbname}")))
201            .execute(&mut conn)
202            .await
203            .map_err(classify_mysql_error)?;
204
205        Ok(())
206    }
207}
208
209/// An open connection to a MySQL database.
210#[derive(Debug)]
211pub struct Connection {
212    conn: MySqlConnection,
213    /// Set to `false` after a connection-level failure. SQLx does not expose a
214    /// passive validity flag, so the driver records one for [`is_valid`].
215    valid: Cell<bool>,
216    query_log: QueryLogConfig,
217    capability: &'static Capability,
218}
219
220impl Connection {
221    /// Wraps an existing SQLx [`MySqlConnection`] as a Toasty connection.
222    pub fn new(conn: MySqlConnection) -> Self {
223        Self::with_capability(conn, &Capability::MYSQL)
224    }
225
226    fn with_capability(conn: MySqlConnection, capability: &'static Capability) -> Self {
227        Self {
228            conn,
229            valid: Cell::new(true),
230            query_log: QueryLogConfig::default(),
231            capability,
232        }
233    }
234
235    async fn exec_sql(
236        &mut self,
237        sql_as_str: &str,
238        args: MySqlArguments,
239        ret: SqlReturn,
240        log: &mut QueryLog<'_>,
241    ) -> Result<ExecResponse> {
242        if matches!(ret, SqlReturn::Count | SqlReturn::LastInsertId(_)) {
243            let result = sqlx::query_with(AssertSqlSafe(sql_as_str), args)
244                .execute(&mut self.conn)
245                .await
246                .map_err(|e| record_mysql_err(&self.valid, e))?;
247
248            if let SqlReturn::LastInsertId(ty) = ret {
249                let id = ty.cast(&(), stmt::Value::U64(result.last_insert_id()))?;
250                log.rows(1);
251                return Ok(ExecResponse::value_stream(stmt::ValueStream::from_vec(
252                    vec![ValueRecord::from_vec(vec![id]).into()],
253                )));
254            }
255
256            return Ok(ExecResponse::count(result.rows_affected()));
257        }
258
259        let rows = sqlx::query_with(AssertSqlSafe(sql_as_str), args)
260            .fetch_all(&mut self.conn)
261            .await
262            .map_err(|e| record_mysql_err(&self.valid, e))?;
263
264        log.rows(rows.len() as u64);
265        let mut records = Vec::with_capacity(rows.len());
266
267        for row in rows {
268            let mut values = Vec::with_capacity(row.len());
269
270            match &ret {
271                SqlReturn::Count | SqlReturn::LastInsertId(_) => unreachable!(),
272                SqlReturn::Infer => {
273                    for i in 0..row.len() {
274                        let column = row.column(i);
275                        values.push(
276                            Value::from_sql_infer(i, &row, column)
277                                .map_err(|e| record_mysql_err(&self.valid, e))?
278                                .into_inner(),
279                        );
280                    }
281                }
282                SqlReturn::Types(returning) => {
283                    assert_eq!(
284                        row.len(),
285                        returning.len(),
286                        "row={row:#?}; returning={returning:#?}"
287                    );
288
289                    for i in 0..row.len() {
290                        let column = row.column(i);
291                        values.push(
292                            Value::from_sql(i, &row, column, &returning[i])
293                                .map_err(|e| record_mysql_err(&self.valid, e))?
294                                .into_inner(),
295                        );
296                    }
297                }
298            }
299
300            records.push(Ok(ValueRecord::from_vec(values)));
301        }
302
303        Ok(ExecResponse::value_stream(stmt::ValueStream::from_iter(
304            records.into_iter(),
305        )))
306    }
307
308    /// Creates a table and its indices from a schema definition.
309    pub async fn create_table(&mut self, schema: &db::Schema, table: &Table) -> Result<()> {
310        let serializer = serializer(self.capability, schema);
311        let statement = serializer.serialize(&sql::Statement::create_table(table, self.capability));
312
313        sqlx::query(AssertSqlSafe(statement))
314            .execute(&mut self.conn)
315            .await
316            .map_err(|e| record_mysql_err(&self.valid, e))?;
317
318        for index in &table.indices {
319            if index.primary_key {
320                continue;
321            }
322
323            let statement = serializer.serialize(&sql::Statement::create_index(index));
324            sqlx::query(AssertSqlSafe(statement))
325                .execute(&mut self.conn)
326                .await
327                .map_err(|e| record_mysql_err(&self.valid, e))?;
328        }
329
330        Ok(())
331    }
332}
333
334impl From<MySqlConnection> for Connection {
335    fn from(conn: MySqlConnection) -> Self {
336        Self::new(conn)
337    }
338}
339
340#[async_trait]
341impl toasty_core::driver::Connection for Connection {
342    async fn exec(&mut self, schema: &Arc<Schema>, op: Operation) -> Result<ExecResponse> {
343        let driver = match self.capability.sql {
344            Some(Dialect::MariaDb) => "mariadb",
345            _ => "mysql",
346        };
347        tracing::trace!(driver, op = %op.name(), "driver exec");
348
349        let (sql, typed_params, ret) = match op {
350            Operation::Insert(op) => {
351                // A surviving RETURNING clause means MariaDB, and a result
352                // set to read. For MySQL the planner strips it and asks for
353                // the auto-increment key alone, via LAST_INSERT_ID().
354                let returns_rows = op.stmt.returning().is_some();
355
356                let ret = match op.ret {
357                    Some(types) if returns_rows => SqlReturn::Types(types),
358                    Some(types) => {
359                        let [ty] = &types[..] else {
360                            return Err(toasty_core::Error::invalid_result(format!(
361                                "MySQL insert ID result requires one type, got {types:?}"
362                            )));
363                        };
364                        SqlReturn::LastInsertId(ty.clone())
365                    }
366                    None => SqlReturn::Count,
367                };
368                (sql::Statement::from(op.stmt), op.params, ret)
369            }
370            Operation::QuerySql(op) => {
371                let ret = match op.ret {
372                    Some(types) => SqlReturn::Types(types),
373                    None => SqlReturn::Count,
374                };
375                (sql::Statement::from(op.stmt), op.params, ret)
376            }
377            Operation::RawSql(op) => {
378                let ret = match op.ret {
379                    RawSqlRet::None => SqlReturn::Count,
380                    RawSqlRet::Infer => SqlReturn::Infer,
381                    RawSqlRet::Types(types) => SqlReturn::Types(types),
382                };
383                let mut log = QueryLog::sql(
384                    &self.query_log,
385                    driver,
386                    &op.sql,
387                    op.params.iter().map(|tv| &tv.value),
388                );
389                let mut args = MySqlArguments::default();
390                for param in op.params {
391                    Value::from(param.value)
392                        .add_to(&mut args)
393                        .map_err(|e| record_mysql_err(&self.valid, e))?;
394                }
395                let result = self.exec_sql(&op.sql, args, ret, &mut log).await;
396                log.finish(&result);
397                return result;
398            }
399            Operation::Transaction(op) => {
400                if let Transaction::Start {
401                    mode: mode @ (TransactionMode::Immediate | TransactionMode::Exclusive),
402                    ..
403                } = &op
404                {
405                    return Err(toasty_core::Error::unsupported_feature(format!(
406                        "{} does not support TransactionMode::{mode:?}",
407                        self.capability.driver_name
408                    )));
409                }
410                let statement = serializer(self.capability, &schema.db).serialize_transaction(&op);
411                sqlx::raw_sql(AssertSqlSafe(statement))
412                    .execute(&mut self.conn)
413                    .await
414                    .map_err(|e| record_mysql_err(&self.valid, e))?;
415                return Ok(ExecResponse::count(0));
416            }
417            op => todo!("op={op:#?}"),
418        };
419
420        let (sql_as_str, arg_order) =
421            serializer(self.capability, &schema.db).serialize_with_arg_order(&sql);
422
423        let mut log = QueryLog::sql(
424            &self.query_log,
425            driver,
426            &sql_as_str,
427            arg_order.iter().map(|&pos| &typed_params[pos].value),
428        );
429
430        // MySQL uses positional `?` placeholders, so parameters must follow the
431        // order in which their `Expr::Arg(n)` values appear in serialized SQL.
432        let mut remaining = vec![0usize; typed_params.len()];
433        for &pos in &arg_order {
434            remaining[pos] += 1;
435        }
436        let mut values = typed_params
437            .into_iter()
438            .map(|param| Some(param.value))
439            .collect::<Vec<_>>();
440        let mut args = MySqlArguments::default();
441        for pos in arg_order {
442            remaining[pos] -= 1;
443            let value = if remaining[pos] == 0 {
444                values[pos].take().expect("MySQL parameter already moved")
445            } else {
446                values[pos]
447                    .as_ref()
448                    .expect("MySQL parameter missing")
449                    .clone()
450            };
451            Value::from(value)
452                .add_to(&mut args)
453                .map_err(|e| record_mysql_err(&self.valid, e))?;
454        }
455
456        let result = self.exec_sql(&sql_as_str, args, ret, &mut log).await;
457        log.finish(&result);
458        result
459    }
460
461    async fn push_schema(&mut self, schema: &Schema) -> Result<()> {
462        for table in &schema.db.tables {
463            tracing::debug!(table = %table.name, "creating table");
464            self.create_table(&schema.db, table).await?;
465        }
466        Ok(())
467    }
468
469    async fn applied_migrations(
470        &mut self,
471    ) -> Result<Vec<toasty_core::schema::db::AppliedMigration>> {
472        sqlx::query(
473            "CREATE TABLE IF NOT EXISTS __toasty_migrations (
474                id BIGINT UNSIGNED PRIMARY KEY,
475                name TEXT NOT NULL,
476                applied_at TIMESTAMP NOT NULL
477            )",
478        )
479        .execute(&mut self.conn)
480        .await
481        .map_err(|e| record_mysql_err(&self.valid, e))?;
482
483        let ids = sqlx::query_scalar::<sqlx::mysql::MySql, u64>(
484            "SELECT id FROM __toasty_migrations ORDER BY applied_at",
485        )
486        .fetch_all(&mut self.conn)
487        .await
488        .map_err(|e| record_mysql_err(&self.valid, e))?;
489
490        Ok(ids
491            .into_iter()
492            .map(toasty_core::schema::db::AppliedMigration::new)
493            .collect())
494    }
495
496    async fn apply_migration(
497        &mut self,
498        id: u64,
499        name: &str,
500        migration: &toasty_core::schema::db::Migration,
501    ) -> Result<()> {
502        tracing::info!(id, name, "applying migration");
503        sqlx::query(
504            "CREATE TABLE IF NOT EXISTS __toasty_migrations (
505                id BIGINT UNSIGNED PRIMARY KEY,
506                name TEXT NOT NULL,
507                applied_at TIMESTAMP NOT NULL
508            )",
509        )
510        .execute(&mut self.conn)
511        .await
512        .map_err(|e| record_mysql_err(&self.valid, e))?;
513
514        let mut transaction = self
515            .conn
516            .begin()
517            .await
518            .map_err(|e| record_mysql_err(&self.valid, e))?;
519
520        for statement in migration.statements() {
521            if let Err(error) = sqlx::raw_sql(AssertSqlSafe(statement))
522                .execute(&mut *transaction)
523                .await
524            {
525                let error = record_mysql_err(&self.valid, error);
526                transaction
527                    .rollback()
528                    .await
529                    .map_err(|e| record_mysql_err(&self.valid, e))?;
530                return Err(error);
531            }
532        }
533
534        if let Err(error) = sqlx::query(
535            "INSERT INTO __toasty_migrations (id, name, applied_at) VALUES (?, ?, NOW())",
536        )
537        .bind(id)
538        .bind(name)
539        .execute(&mut *transaction)
540        .await
541        {
542            let error = record_mysql_err(&self.valid, error);
543            transaction
544                .rollback()
545                .await
546                .map_err(|e| record_mysql_err(&self.valid, e))?;
547            return Err(error);
548        }
549
550        transaction
551            .commit()
552            .await
553            .map_err(|e| record_mysql_err(&self.valid, e))?;
554        Ok(())
555    }
556
557    fn is_valid(&self) -> bool {
558        self.valid.get()
559    }
560
561    async fn ping(&mut self) -> Result<()> {
562        match self.conn.ping().await {
563            Ok(()) => Ok(()),
564            Err(error) => {
565                self.valid.set(false);
566                Err(toasty_core::Error::connection_lost(error))
567            }
568        }
569    }
570}