mysql
This create offers:
- MySql database driver in pure rust;
- connection pool.
Features:
- macOS, Windows and Linux support;
- TLS support via nativetls create;
- 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;
- optional per-connection cache of prepared statements;
- 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.
Installation
Put the desired version of the crate into the dependencies
section of your Cargo.toml
:
[]
= "*"
Example
use *;
use *;
let url = "mysql://root:password@localhost:3307/db_name";
let pool = new?;
let mut conn = pool.get_conn?;
// Let's create a table for payments.
conn.query_drop?;
let payments = vec!;
// Now let's insert payments to the database
conn.exec_batch?;
// Let's select payments from database. Type inference should do the trick here.
let selected_payments = conn
.query_map?;
// Let's make sure, that `payments` equals to `selected_payments`.
// Mysql gives no guaranties on order of returned rows
// without `ORDER BY`, so assume we are lucky.
assert_eq!;
println!;
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:
let _ = from_url?;
let _ = from_url?;
let _ = from_url?;
Supported URL parameters (for the meaning of each field please refer to the docs on Opts
structure in the create API docs):
prefer_socket: true | false
- defines the value of the same field in theOpts
structure;tcp_keepalive_time_ms: u32
- defines the value (in milliseconds) of thetcp_keepalive_time
field in theOpts
structure;tcp_connect_timeout_ms: u64
- defines the value (in milliseconds) of thetcp_connect_timeout
field in theOpts
structure;stmt_cache_size: u32
- defines the value of the same field in theOpts
structure;compress
- defines the value of the same field in theOpts
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.
let opts = new
.user
.db_name;
let _ = new?;
Conn
This structure represents an active MySql connection. It also holds statement cache and metadata for the last result set.
Transaction
It's a simple wrapper on top of a routine, that starts with START TRANSACTION
and ends with COMMIT
or ROLBACK
.
use *;
use *;
let pool = new?;
let mut conn = pool.get_conn?;
let mut tx = conn.start_transaction?;
tx.query_drop?;
tx.exec_drop?;
let val: = tx.query_first?;
assert_eq!;
// Note, that transaction will be rolled back implicitly on Drop, if not committed.
tx.rollback;
let val: = conn.query_first?;
assert_eq!;
Pool
It's a reference to a connection pool, that can be cloned and shared between threads.
use *;
use *;
use spawn;
let pool = new?;
let handles = .map;
let result: = handles.map.collect;
assert_eq!;
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).
use *;
use *;
let pool = new?;
let mut conn = pool.get_conn?;
let stmt = conn.prep?;
// The prepared statement will return no columns.
assert!;
// The prepared statement have one parameter.
let param = stmt.params.get.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
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 ofValue
there existT: FromValue
such thatfrom_value
will never panic. This means, that if your database schema is known, than it's possible to write your application using onlyfrom_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.
use *;
use *;
let via_test_protocol: u32 = from_value;
let via_bin_protocol: u32 = from_value;
assert_eq!;
let unknown_val = // ...
// Maybe it is a float?
let unknown_val = match ;
// Or a string?
let unknown_val = match ;
// Screw this, I'll simply match on it
match unknown_val
Row
Internally Row
is a vector of Value
s, 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 asfrom_value
, but for rows;from_row_opt(Row) -> Option<T>
- same asfrom_value_opt
, but for rows.
[Queryable
][#queryable] trait offers implicit conversion for rows of a query result,
that is based on this trait.
use *;
use *;
let mut conn = new?;
// Single-column row can be converted to a singular value
let val: = conn.query_first?;
assert_eq!;
// Example of a mutli-column row conversion to an inferred type.
let row = conn.query_first?;
assert_eq!;
// Some unknown row
let row: Row = conn.query_first?.unwrap;
for column in row.columns_ref
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).
use *;
use *;
let mut conn = new?;
// Singular tuple requires extra comma:
let row: = conn.exec_first?;
assert_eq!;
// More than 12 parameters:
let row: = conn.exec_first?;
assert_eq!;
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.
use *;
use *;
/// Serializable structure.
// Value::from for Serialized will emit json string.
let value = from;
assert_eq!;
// from_value for Deserialized will parse json string.
let structure: = from_value;
assert_eq!;
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
Queryalbe
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.
use *;
use *;
let mut conn = new?;
// This query will emit two result sets.
let mut result = conn.query_iter?;
let mut sets = 0;
while let Some = result.next_set
assert_eq!;
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:
let pool = new?;
let val = pool.get_conn?.query_first?;
// Text protocol returns bytes even though the result of POW
// is actually a floating point number.
assert_eq!;
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
:
use *;
use *;
let pool = new?;
let it = iter?;
assert_eq!;
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:
let pool = new?;
let val = pool.get_conn?.exec_first?;
assert_eq!;
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, containe
in the Statement
structure.
let pool = new?;
let mut conn_1 = pool.get_conn?;
let mut conn_2 = pool.get_conn?;
let stmt_1 = conn_1.prep?;
// stmt_1 is for the conn_1, ..
assert!;
assert!;
// .. so stmt_1 will execute only on conn_1
assert!;
assert!;
Statement cache
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 ofstmt_cache_size
is greater, than you could receive an error while prepareing 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 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 a parameters for execution.
Note: Positional and named parameters can't be mixed within the single statement.
Examples:
let pool = new?;
let mut conn = pool.get_conn?;
let stmt = conn.prep?;
let foo = 42;
let val_13 = conn.exec_first?.unwrap;
// Short syntax is available when param name is the same as variable name:
let val_42 = conn.exec_first?.unwrap;
assert_eq!;
assert_eq!;
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:
use *;
use *;
let pool = new?;
let result: = "SELECT ?, ?, ?"
.with // <- WithParams::with will construct an instance of QueryWithParams
.first?; // <- QueryWithParams is executed on the given pool
assert_eq!;
The BatchQuery
trait is a helper for batch statement execution. It's implemented for
QueryWithParams
where parameters is an iterator over parameters:
use *;
use *;
let pool = new?;
let mut conn = pool.get_conn?;
"CREATE TEMPORARY TABLE batch (x INT)".run?;
"INSERT INTO batch (x) VALUES (?)"
.with // <- QueryWithParams constructed with an iterator
.batch?; // <- batch execution is preformed here
let result: = "SELECT x FROM batch".fetch?;
assert_eq!;
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 getQueryRestul
;prep
- basic method to prepare a statement;exec_iter
- basic method to execute statement and getQueryResult
;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 firt result set, other result sets will be dropped:
{query|exec}
- to collect the result into aVec<T: FromRow>
;{query|exec}_first
- to get the firstT: FromRow
, if any;{query|exec}_map
- to map eachT: FromRow
to someU
;{query|exec}_fold
- to fold the set ofT: 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.
Changelog
Available here
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.