Crates.io Build Status Build Status

mysql

This create offers:

Features:

Installation

Put the desired version of the crate into the dependencies section of your Cargo.toml:

toml [dependencies] mysql = "*"

Example

```rust use mysql::; use mysql::prelude::;

[derive(Debug, PartialEq, Eq)]

struct Payment { customerid: i32, amount: i32, accountname: Option, }

let url = "mysql://root:password@localhost:3307/db_name";

let pool = Pool::new(url)?;

let mut conn = pool.get_conn()?;

// Let's create a table for payments. conn.querydrop( r"CREATE TEMPORARY TABLE payment ( customerid int not null, amount int not null, account_name text )")?;

let payments = vec![ Payment { customerid: 1, amount: 2, accountname: None }, Payment { customerid: 3, amount: 4, accountname: Some("foo".into()) }, Payment { customerid: 5, amount: 6, accountname: None }, Payment { customerid: 7, amount: 8, accountname: None }, Payment { customerid: 9, amount: 10, accountname: Some("bar".into()) }, ];

// Now let's insert payments to the database conn.execbatch( r"INSERT INTO payment (customerid, amount, accountname) VALUES (:customerid, :amount, :accountname)", payments.iter().map(|p| params! { "customerid" => p.customerid, "amount" => p.amount, "accountname" => &p.account_name, }) )?;

// Let's select payments from database. Type inference should do the trick here. let selectedpayments = conn .querymap( "SELECT customerid, amount, accountname from payment", |(customerid, amount, accountname)| { Payment { customerid, amount, accountname } }, )?;

// 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. asserteq!(payments, selectedpayments); println!("Yay!"); ```

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:

rust let _ = Opts::from_url("mysql://localhost/some_db")?; let _ = Opts::from_url("mysql://[::1]/some_db")?; let _ = Opts::from_url("mysql://user:pass%20word@127.0.0.1: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):

OptsBuilder

It's a convenient builder for the Opts structure. It defines setters for fields of the Opts structure.

rust let opts = OptsBuilder::new() .user(Some("foo")) .db_name(Some("bar")); let _ = Conn::new(opts)?;

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.

```rust use mysql::; use mysql::prelude::;

let pool = Pool::new(getopts())?; let mut conn = pool.getconn()?;

let mut tx = conn.starttransaction(false, None, None)?; tx.querydrop("CREATE TEMPORARY TABLE tmp (TEXT a)")?; tx.execdrop("INSERT INTO tmp (a) VALUES (?)", ("foo",))?; let val: Option = tx.queryfirst("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.queryfirst("SELECT a from tmp")?; asserteq!(val, None); ```

Pool

It's a reference to a connection pool, that can be cloned and shared between threads.

```rust 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.getconn()?; conn.execfirst::("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]); ```

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).

```rust use mysql::; use mysql::prelude::;

let pool = Pool::new(getopts())?; let mut conn = pool.getconn()?;

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(); asserteq!(param.schemastr(), ""); asserteq!(param.tablestr(), ""); asserteq!(param.namestr(), "?"); ```

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:

```rust use mysql::; use mysql::prelude::;

let viatestprotocol: u32 = fromvalue(Value::Bytes(b"65536".tovec())); let viabinprotocol: u32 = fromvalue(Value::UInt(65536)); asserteq!(viatestprotocol, viabinprotocol);

let unknown_val = // ...

// Maybe it is a float? let unknownval = match fromvalueopt::(unknownval) { Ok(float) => { println!("A float value: {}", float); return Ok(()); } Err(FromValueError(unknownval)) => unknownval, };

// Or a string? let unknownval = match fromvalueopt::(unknownval) { Ok(string) => { println!("A string value: {}", string); return Ok(()); } Err(FromValueError(unknownval)) => unknownval, };

// Screw this, I'll simply match on it match unknownval { val @ Value::NULL => { println!("An empty value: {:?}", fromvalue::>(val)) }, val @ Value::Bytes(..) => { // It's non-utf8 bytes, since we already tried to convert it to String println!("Bytes: {:?}", fromvalue::>(val)) } val @ Value::Int(..) => { println!("A signed integer: {}", fromvalue::(val)) } val @ Value::UInt(..) => { println!("An unsigned integer: {}", fromvalue::(val)) } Value::Float(..) => unreachable!("already tried"), val @ Value::Date(..) => { use mysql::chrono::NaiveDateTime; println!("A date value: {}", fromvalue::(val)) } val @ Value::Time(..) => { use std::time::Duration; println!("A time value: {:?}", from_value::(val)) } } ```

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:

[Queryable][#queryable] trait offers implicit conversion for rows of a query result, that is based on this trait.

```rust use mysql::; use mysql::prelude::;

let mut conn = Conn::new(get_opts())?;

// Single-column row can be converted to a singular value let val: Option = conn.queryfirst("SELECT 'foo'")?; asserteq!(val.unwrap(), "foo");

// Example of a mutli-column row conversion to an inferred type. let row = conn.queryfirst("SELECT 255, 256")?; asserteq!(row, Some((255u8, 256u16)));

// Some unknown row let row: Row = conn.query_first( // ... # "SELECT 255, Null", )?.unwrap();

for column in row.columnsref() { let columnvalue = &row[column.namestr().asref()]; println!( "Column {} of type {:?} with value {:?}", column.namestr(), column.columntype(), column_value, ); } ```

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:

```rust use mysql::; use mysql::prelude::;

let mut conn = Conn::new(get_opts())?;

// Singular tuple requires extra comma: let row: Option = conn.execfirst("SELECT ?", (0,))?; asserteq!(row.unwrap(), 0);

// More than 12 parameters: let row: Option = conn.execfirst( "SELECT ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ? + ?", (0..16).collect::>(), )?; asserteq!(row.unwrap(), 120); ```

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.

```rust use mysql::; use mysql::prelude::;

/// 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 })); asserteq!(value, Value::Bytes(br#"{"foo":42}"#.tovec()));

// fromvalue for Deserialized will parse json string. let structure: Deserialized = fromvalue(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 result set iteration. For other cases Conn 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.

```rust use mysql::; use mysql::prelude::;

let mut conn = Conn::new(get_opts())?;

// This query will emit two result sets. let mut result = conn.query_iter("SELECT 1, 2; SELECT 3, 3.14;")?;

let mut set = 0; while result.moreresultsexists() { println!("Result set columns: {:?}", result.columns_ref());

for row in result.by_ref() {
    match set {
        0 => {
            // First result set will contain two numbers.
            assert_eq!((1_u8, 2_u8), from_row(row?));
        }
        1 => {
            // Second result set will contain a number and a float.
            assert_eq!((3_u8, 3.14), from_row(row?));
        }
        _ => unreachable!(),
    }
}
set += 1;

} ```

Text protocol

MySql text protocol is implemented in the set of Conn::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:

```rust let pool = Pool::new(getopts())?; let val = pool.getconn()?.query_first("SELECT POW(2, 16)")?;

// Text protocol returns bytes even though the result of POW // is actually a floating point number. asserteq!(val, Some(Value::Bytes("65536".asbytes().to_vec()))); ```

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:

```rust let pool = Pool::new(getopts())?; let val = pool.getconn()?.exec_first("SELECT POW(?, ?)", (2, 16))?;

assert_eq!(val, Some(Value::Float(65536.0))); ```

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 a connection in any way, but one can look on to the connection id, that is stored in the Statement structure.

```rust let pool = Pool::new(get_opts())?;

let mut conn1 = pool.getconn()?; let mut conn2 = pool.getconn()?;

let stmt1 = conn1.prep("SELECT ?")?;

// stmt1 is for the conn1, .. assert!(stmt1.connectionid() == conn1.connectionid()); assert!(stmt1.connectionid() != conn2.connectionid());

// .. so stmt1 will execute only on conn1 assert!(conn1.execdrop(&stmt1, ("foo",)).isok()); assert!(conn2.execdrop(&stmt1, ("foo",)).iserr()); ```

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:

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:

```rust let pool = Pool::new(get_opts())?;

let mut conn = pool.get_conn()?; let stmt = conn.prep("SELECT :foo, :bar, :foo")?;

let foo = 42;

let val13 = conn.execfirst(&stmt, params! { "foo" => 13, "bar" => foo })?.unwrap(); // Short syntax is available when param name is the same as variable name: let val42 = conn.execfirst(&stmt, params! { foo, "bar" => 13 })?.unwrap();

asserteq!((foo, 13, foo), val42); asserteq!((13, foo, 13), val13); ```

Queryable

The Queryable trait defines common methods for Conn, PooledConn and Transaction. The set of basic methods consts of:

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:

The trait also defines additional helper for a batch statement execution.

Changelog

Available here

License

Licensed under either of

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.