Mysql client library implemented in rust.
This crate offers:
Features:
Opts::get_enable_cleartext_plugin].Put the desired version of the crate into the dependencies section of your Cargo.toml:
[dependencies]
mysql = "*"…feature sets:
buffer-pool flate2/zlib and derivedefault but with flate2/rust_backend instead of flate2/zlibflate2/zlib onlyflate2/rust_backend onlyfeatures:
prelude
(see [corresponding section][derive_docs] in the mysql_common documentation)TLS/SSL related features:
native-tls as the TLS backend
(see the SSL Support section)rustls as the TLS backend using aws-lc-rs crypto provider
(see the SSL Support section)rustls as the TLS backend using ring crypto provider
(see the SSL Support section)rustls as the TLS backend without crypto provider
(see the SSL Support section)features proxied from mysql_common:
Please note, that you'll need to reenable required features if you are using default-features = false:
[dependencies]
# Lets say that we want to use only the `rustls-tls` feature:
mysql = { version = "*", default-features = false, features = ["minimal-rust", "rustls-tls"] }Please refer to the [crate docs].
OptsThis structure holds server host name, client username/password and other settings, that controls client behavior.
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:
let _ = Opts::from_url("mysql://localhost/some_db")?;
let _ = Opts::from_url("mysql://[::1]/some_db")?;
let _ = Opts::from_url("mysql://user:pass%[email protected]:3307/some_db?")?;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 namepassword: 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.OptsBuilderIt's a convenient builder for the Opts structure. It defines setters for fields
of the Opts structure.
let opts = OptsBuilder::new()
.user(Some("foo"))
.db_name(Some("bar"));
let _ = Conn::new(opts)?;ConnThis 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.
TransactionIt's a simple wrapper on top of a routine, that starts with START TRANSACTION
and ends with COMMIT or ROLLBACK.
use mysql::*;
use mysql::prelude::*;
let pool = Pool::new(get_opts())?;
let mut conn = pool.get_conn()?;
let mut tx = conn.start_transaction(TxOpts::default())?;
tx.query_drop("CREATE TEMPORARY TABLE tmp (TEXT a)")?;
tx.exec_drop("INSERT INTO tmp (a) VALUES (?)", ("foo",))?;
let val: Option = tx.query_first("SELECT a from tmp")?;
assert_eq!(val.unwrap(), "foo");
// Note, that transaction will be rolled back implicitly on Drop, if not committed.
tx.rollback();
let val: Option = conn.query_first("SELECT a from tmp")?;
assert_eq!(val, None);PoolIt's a reference to a connection pool, that can be cloned and shared between threads.
use mysql::*;
use mysql::prelude::*;
use std::thread::spawn;
let pool = Pool::new(get_opts())?;
let handles = (0..4).map(|i| {
spawn({
let pool = pool.clone();
move || {
let mut conn = pool.get_conn()?;
conn.exec_first::("SELECT ? * 10", (i,))
.map(Option::unwrap)
}
})
});
let result: Result> = handles.map(|handle| handle.join().unwrap()).collect();
assert_eq!(result.unwrap(), vec![0, 10, 20, 30]);StatementStatement, 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).
use mysql::*;
use mysql::prelude::*;
let pool = Pool::new(get_opts())?;
let mut conn = pool.get_conn()?;
let stmt = conn.prep("DO ?")?;
// The prepared statement will return no columns.
assert!(stmt.columns().is_empty());
// The prepared statement have one parameter.
let param = stmt.params().get(0).unwrap();
assert_eq!(param.schema_str(), "");
assert_eq!(param.table_str(), "");
assert_eq!(param.name_str(), "?");ValueThis enumeration represents the raw value of a MySql cell. Library offers conversion between
Value and different rust types via FromValue trait described below.
FromValue traitThis trait is reexported from mysql_common create. Please refer to its [crate docs][mysql_common 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 - non-panicking, but less convenient conversion.
This function is useful to probe conversion in cases, where source database schema is unknown.
…RowInternally 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 traitThis trait is reexported from mysql_common create. Please refer to its [crate docs][mysql_common 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 - 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.
…ParamsRepresents parameters of a prepared statement, but this type won't appear directly in your code
because binary protocol API will ask for T: Into, where Into is implemented:
for tuples of Into types up to arity 12;
Note: singular tuple requires extra comma, e.g. ("foo",);
for IntoIterator> for cases, when your statement takes more
than 12 parameters;
for named parameters representation (the value of the params! macro, described below).
use mysql::*;
use mysql::prelude::*;
let mut conn = Conn::new(get_opts())?;
// Singular tuple requires extra comma:
let row: Option = conn.exec_first("SELECT ?", (0,))?;
assert_eq!(row.unwrap(), 0);
// More than 12 parameters:
let row: Option = conn.exec_first(
"SELECT CONVERT(? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ?, UNSIGNED)",
(0..16).collect::>(),
)?;
assert_eq!(row.unwrap(), 120);Note: Please refer to the [mysql_common crate docs][mysql_common docs] for the list
of types, that implements Into.
Serialized, DeserializedWrapper 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.
use mysql::*;
use mysql::prelude::*;
use serde::{Deserialize, Serialize};
/// Serializable structure.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Example {
foo: u32,
}
// Value::from for Serialized will emit json string.
let value = Value::from(Serialized(Example { foo: 42 }));
assert_eq!(value, Value::Bytes(br#"{"foo":42}"#.to_vec()));
// from_value for Deserialized will parse json string.
let structure: Deserialized = from_value(value);
assert_eq!(structure, Deserialized(Example { foo: 42 }));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 resul
No open issues yet, or sync has not completed.