This crate offers:
- MySql database driver in pure rust;
- connection pool.
Features:
- macOS, Windows and Linux support;
- TLS support via native-tls or rustls (see the SSL Support section);
- MySql text protocol support, i.e. support of simple text queries and text result sets;
- MySql binary protocol support, i.e. support of prepared statements and binary result sets;
- support of multi-result sets;
- support of named parameters for prepared statements (see the Named Parameters section);
- per-connection cache of prepared statements (see the Statement Cache section);
- buffer pool (see the Buffer Pool section);
- support of MySql packets larger than 2^24;
- support of Unix sockets and Windows named pipes;
- support of custom LOCAL INFILE handlers;
- support of MySql protocol compression;
- support of auth plugins:
- mysql_native_password - for MySql prior to v8;
- caching_sha2_password - for MySql v8 and higher;
- mysql_clear_password - opt-in (see Opts::get_enable_cleartext_plugin.
§Installation
Put the desired version of the crate into the dependencies section of your Cargo.toml:
§Example
§Crate Features
-
feature sets:
- default – includes buffer-pool flate2/zlib and derive
- default-rust - same as default but with flate2/rust_backend instead of flate2/zlib
- minimal - includes flate2/zlib only
- minimal-rust - includes flate2/rust_backend only
-
features:
- buffer-pool – enables buffer pooling (see the Buffer Pool section)
- derive – reexports derive macros under prelude (see corresponding section in the mysql_common documentation)
-
TLS/SSL related features:
- native-tls – specifies native-tls as the TLS backend (see the SSL Support section)
- rustls-tls – specifies rustls as the TLS backend using aws-lc-rs crypto provider (see the SSL Support section)
- rustls-tls-ring – specifies rustls as the TLS backend using ring crypto provider (see the SSL Support section)
- rustls - specifies rustls as the TLS backend without crypto provider (see the SSL Support section)
-
features proxied from mysql_common:
- derive - see this table.
- chrono - see this table.
- time - see this table.
- bigdecimal - see this table.
- rust_decimal - see this table.
- frunk - see this table.
- binlog - see this table.
Please note, that you’ll need to reenable required features if you are using default-features = false:
§API Documentation
Please refer to the crate docs.
§Basic structures
§Opts
This structure holds server host name, client username/password and other settings, that controls client behavior.
§URL-based connection string
Note, that you can use URL-based connection string as a source of an Opts instance. URL schema must be mysql. Host, port and credentials, as well as query parameters, should be given in accordance with the RFC 3986.
Examples:
Supported URL parameters (for the meaning of each field please refer to the docs on Opts structure in the create API docs):
- user: string – MySql client user name
- password: string – MySql client password;
- db_name: string – MySql database name;
- host: Host – MySql server hostname/ip;
- port: u16 – MySql server port;
- pool_min: usize – see PoolConstraints::min;
- pool_max: usize – see PoolConstraints::max;
- prefer_socket: true | false - see Opts::get_prefer_socket;
- tcp_keepalive_time_ms: u32 - defines the value (in milliseconds) of the tcp_keepalive_time field in the Opts structure;
- tcp_keepalive_probe_interval_secs: u32 - defines the value of the tcp_keepalive_probe_interval_secs field in the Opts structure;
- tcp_keepalive_probe_count: u32 - defines the value of the tcp_keepalive_probe_count field in the Opts structure;
- tcp_connect_timeout_ms: u64 - defines the value (in milliseconds) of the tcp_connect_timeout field in the Opts structure;
- tcp_user_timeout_ms - defines the value (in milliseconds) of the tcp_user_timeout field in the Opts structure;
- stmt_cache_size: u32 - defines the value of the same field in the Opts structure;
- enable_cleartext_plugin – see Opts::get_enable_cleartext_plugin;
- secure_auth – see Opts::get_secure_auth;
- reset_connection – see PoolOpts::reset_connection;
- check_health – see PoolOpts::check_health;
- compress - defines the value of the same field in the Opts structure.
Supported value are:
- true - enables compression with the default compression level;
- fast - enables compression with “fast” compression level;
- best - enables compression with “best” compression level;
- 1..9 - enables compression with the given compression level.
- socket - socket path on UNIX, or pipe name on Windows.
§OptsBuilder
It’s a convenient builder for the Opts structure. It defines setters for fields of the Opts structure.
§Conn
This structure represents an active MySql connection. It also holds statement cache and metadata for the last result set.
Conn’s destructor will gracefully disconnect it from the server.
§Transaction
It’s a simple wrapper on top of a routine, that starts with START TRANSACTION and ends with COMMIT or ROLLBACK.
§Pool
It’s a reference to a connection pool, that can be cloned and shared between threads.
§Statement
Statement, actually, is just an identifier coupled with statement metadata, i.e an information about its parameters and columns. Internally the Statement structure also holds additional data required to support named parameters (see bellow).
§Value
This enumeration represents the raw value of a MySql cell. Library offers conversion between Value and different rust types via FromValue trait described below.
§FromValue trait
This trait is reexported from mysql_common create. Please refer to its crate docs for the list of supported conversions.
Trait offers conversion in two flavours:
-
from_value(Value) -> T - convenient, but panicking conversion.
Note, that for any variant of Value there exist a type, that fully covers its domain, i.e. for any variant of Value there exist T: FromValue such that from_value will never panic. This means, that if your database schema is known, then it’s possible to write your application using only from_value with no fear of runtime panic.
-
from_value_opt(Value) -> Option<T> - non-panicking, but less convenient conversion.
This function is useful to probe conversion in cases, where source database schema is unknown.
§Row
Internally Row is a vector of Values, that also allows indexing by a column name/offset, and stores row metadata. Library offers conversion between Row and sequences of Rust types via FromRow trait described below.
§FromRow trait
This trait is reexported from mysql_common create. Please refer to its crate docs for the list of supported conversions.
This conversion is based on the FromValue and so comes in two similar flavours:
- from_row(Row) -> T - same as from_value, but for rows;
- from_row_opt(Row) -> Option<T> - same as from_value_opt, but for rows.
Queryable trait offers implicit conversion for rows of a query result, that is based on this trait.
§Params
Represents parameters of a prepared statement, but this type won’t appear directly in your code because binary protocol API will ask for T: Into<Params>, where Into<Params> is implemented:
-
for tuples of Into<Value> types up to arity 12;
Note: singular tuple requires extra comma, e.g. ("foo",);
-
for IntoIterator<Item: Into<Value>> for cases, when your statement takes more than 12 parameters;
-
for named parameters representation (the value of the params! macro, described below).
Note: Please refer to the mysql_common crate docs for the list of types, that implements Into<Value>.
§Serialized, Deserialized
Wrapper structures for cases, when you need to provide a value for a JSON cell, or when you need to parse JSON cell as a struct.
§QueryResult
It’s an iterator over rows of a query result with support of multi-result sets. It’s intended for cases when you need full control during result set iteration. For other cases Queryable provides a set of methods that will immediately consume the first result set and drop everything else.
This iterator is lazy so it won’t read the result from server until you iterate over it. MySql protocol is strictly sequential, so Conn will be mutably borrowed until the result is fully consumed (please also look at QueryResult::iter docs).
§Text protocol
MySql text protocol is implemented in the set of Queryable::query* methods. It’s useful when your query doesn’t have parameters.
Note: All values of a text protocol result set will be encoded as strings by the server, so from_value conversion may lead to additional parsing costs.
Examples:
§The TextQuery trait.
The TextQuery trait covers the set of Queryable::query* methods from the perspective of a query, i.e. TextQuery is something, that can be performed if suitable connection is given. Suitable connections are:
- &Pool
- Conn
- PooledConn
- &mut Conn
- &mut PooledConn
- &mut Transaction
The unique characteristic of this trait, is that you can give away the connection and thus produce QueryResult that satisfies 'static:
§Binary protocol and prepared statements.
MySql binary protocol is implemented in prep, close and the set of exec* methods, defined on the Queryable trait. Prepared statements is the only way to pass rust value to the MySql server. MySql uses ? symbol as a parameter placeholder and it’s only possible to use parameters where a single MySql value is expected. For example:
§Statements
In MySql each prepared statement belongs to a particular connection and can’t be executed on another connection. Trying to do so will lead to an error. The driver won’t tie statement to its connection in any way, but one can look on to the connection id, contained in the Statement structure.
§Statement cache
§Note
Statement cache only works for:
- for raw Conn
- for PooledConn:
- within its lifetime if PoolOpts::reset_connection is true
- within the lifetime of a wrapped Conn if PoolOpts::reset_connection is false
§Description
Conn will manage the cache of prepared statements on the client side, so subsequent calls to prepare with the same statement won’t lead to a client-server roundtrip. Cache size for each connection is determined by the stmt_cache_size field of the Opts structure. Statements, that are out of this boundary will be closed in LRU order.
Statement cache is completely disabled if stmt_cache_size is zero.
Caveats:
-
disabled statement cache means, that you have to close statements yourself using Conn::close, or they’ll exhaust server limits/resources;
-
you should be aware of the max_prepared_stmt_count option of the MySql server. If the number of active connections times the value of stmt_cache_size is greater, than you could receive an error while preparing another statement.
§Named parameters
MySql itself doesn’t have named parameters support, so it’s implemented on the client side. One should use :name as a placeholder syntax for a named parameter. Named parameters uses the following naming convention:
- parameter name must start with either _ or a..z
- parameter name may continue with _, a..z and 0..9
Named parameters may be repeated within the statement, e.g SELECT :foo, :foo will require a single named parameter foo that will be repeated on the corresponding positions during statement execution.
One should use the params! macro to build parameters for execution.
Note: Positional and named parameters can’t be mixed within the single statement.
Examples:
§Buffer pool
Crate uses the global lock-free buffer pool for the purpose of IO and data serialization/deserialization, that helps to avoid allocations for basic scenarios. You can control its characteristics using the following environment variables:
-
RUST_MYSQL_BUFFER_POOL_CAP (defaults to 128) – controls the pool capacity. Dropped buffer will be immediately deallocated if the pool is full. Set it to 0 to disable the pool at runtime.
-
RUST_MYSQL_BUFFER_SIZE_CAP (defaults to 4MiB) – controls the maximum capacity of a buffer stored in the pool. Capacity of a dropped buffer will be shrunk to this value when buffer is returned to the pool.
To completely disable the pool (say you are using jemalloc) please remove the buffer-pool feature from the set of default crate features (see the Crate Features section).
§BinQuery and BatchQuery traits.
BinQuery and BatchQuery traits covers the set of Queryable::exec* methods from the perspective of a query, i.e. BinQuery is something, that can be performed if suitable connection is given (see TextQuery section for the list of suitable connections).
As with the TextQuery you can give away the connection and acquire QueryResult that satisfies 'static.
BinQuery is for prepared statements, and prepared statements requires a set of parameters, so BinQuery is implemented for QueryWithParams structure, that can be acquired, using WithParams trait.
Example:
The BatchQuery trait is a helper for batch statement execution. It’s implemented for QueryWithParams where parameters is an iterator over parameters:
§Queryable
The Queryable trait defines common methods for Conn, PooledConn and Transaction. The set of basic methods consts of:
- query_iter - basic methods to execute text query and get QueryResult;
- prep - basic method to prepare a statement;
- exec_iter - basic method to execute statement and get QueryResult;
- close - basic method to close the statement;
The trait also defines the set of helper methods, that is based on basic methods. These methods will consume only the first result set, other result sets will be dropped:
- {query|exec} - to collect the result into a Vec<T: FromRow>;
- {query|exec}_first - to get the first T: FromRow, if any;
- {query|exec}_map - to map each T: FromRow to some U;
- {query|exec}_fold - to fold the set of T: FromRow to a single value;
- {query|exec}_drop - to immediately drop the result.
The trait also defines the exec_batch function, which is a helper for batch statement execution.
§SSL Support
SSL support comes in two flavors:
-
Based on the native-tls crate – native TLS backend.
This uses the native OS SSL/TLS provider. Enabled by the rustls-tls feature.
-
Based on the rustls – TLS backend written in Rust. You have three options here:
- rustls-tls feature enables rustls backend with aws-lc-rs crypto provider
- rustls-tls-ring feature enables rustls backend with ring crypto provider
- rustls feature enables rustls backend without crypto provider — you have to install your own provider to avoid “no process-level CryptoProvider available” error (see relevant section of the rustls crate docs)
Please also note a few things about rustls:
- it will fail if you’ll try to connect to the server by its IP address, hostname is required;
- it, most likely, won’t work on windows, at least with default server certs, generated by the MySql installer.
.png)

