[][src]Crate mysql_async

mysql-async

Tokio based asynchronous MySql client library for rust programming language.

Installation

Library hosted on crates.io.

[dependencies]
mysql_async = "<desired version>"

Example

extern crate futures;
#[macro_use]
extern crate mysql_async as my;
extern crate tokio;
// ...

use futures::Future;
use my::prelude::*;

#[derive(Debug, PartialEq, Eq, Clone)]
struct Payment {
    customer_id: i32,
    amount: i32,
    account_name: Option<String>,
}

/// Same as `tokio::run`, but will panic if future panics and will return the result
/// of future execution.
pub fn run<F, T, U>(future: F) -> Result<T, U>
where
    F: Future<Item = T, Error = U> + Send + 'static,
    T: Send + 'static,
    U: Send + 'static,
{
    let mut runtime = tokio::runtime::Runtime::new().unwrap();
    let result = runtime.block_on(future);
    runtime.shutdown_on_idle().wait().unwrap();
    result
}

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


    let pool = my::Pool::new(database_url);
    let future = pool.get_conn().and_then(|conn| {
        // Create temporary table
        conn.drop_query(
            r"CREATE TEMPORARY TABLE payment (
                customer_id int not null,
                amount int not null,
                account_name text
            )"
        )
    }).and_then(move |conn| {
        // Save payments
        let params = payments_clone.into_iter().map(|payment| {
            params! {
                "customer_id" => payment.customer_id,
                "amount" => payment.amount,
                "account_name" => payment.account_name.clone(),
            }
        });

        conn.batch_exec(r"INSERT INTO payment (customer_id, amount, account_name)
                        VALUES (:customer_id, :amount, :account_name)", params)
    }).and_then(|conn| {
        // Load payments from database.
        conn.prep_exec("SELECT customer_id, amount, account_name FROM payment", ())
    }).and_then(|result| {
        // Collect payments
        result.map_and_drop(|row| {
            let (customer_id, amount, account_name) = my::from_row(row);
            Payment {
                customer_id: customer_id,
                amount: amount,
                account_name: account_name,
            }
        })
    }).and_then(|(_ /* conn */, payments)| {
        // The destructor of a connection will return it to the pool,
        // but pool should be disconnected explicitly because it's
        // an asynchronous procedure.
        pool.disconnect().map(|_| payments)
    });

    let loaded_payments = run(future).unwrap();
    assert_eq!(loaded_payments, payments);
}

Re-exports

pub use mysql_common::chrono;
pub use mysql_common::time;
pub use mysql_common::uuid;

Modules

consts
error

Errors used in this crate

futures

Futures used in this crate

params
prelude

Traits used in this crate

Macros

params

This macro is a convenient way to pass named parameters to a statement.

Structs

BinaryProtocol

Phantom struct used to specify MySql binary protocol.

Column

Represents MySql Column (column packet).

Conn
Deserialized

Use it to parse T: Deserialize from Value.

FromRowError

FromRow conversion error.

FromValueError

FromValue conversion error.

Opts

Mysql connection options.

OptsBuilder

Provides a way to build Opts.

Pool

Asynchronous pool of MySql connections.

PoolConstraints

Connection pool constraints.

QueryResult

Result of a query or statement execution.

Row

Client side representation of a MySql row.

Serialized

Use it to pass T: Serialize as JSON to a prepared statement.

SslOpts

Ssl Options.

Stmt

Prepared statement

TextProtocol

Phantom struct used to specify MySql text protocol.

Transaction

This struct represents MySql transaction.

TransactionOptions

Options for transaction

WhiteListFsLocalInfileHandler

Handles local infile requests from filesystem using explicit path white list.

Enums

IsolationLevel

Transaction isolation level.

Params

Representations of parameters of a prepared statement.

Value

Client side representation of a value of MySql column.

Traits

MyFuture

Alias for Future with library error as Future::Error.

Functions

from_row

Will panic if could not convert row to T.

from_row_opt

Will return Err(row) if could not convert row to T

from_value

Will panic if could not convert v to T

from_value_opt

Will return Err(FromValueError(v)) if could not convert v to T

Type Definitions

BoxFuture