rust-mysql-simple support library for the r2d2 connection pool

Related tags

Database r2d2-mysql
Overview

r2d2-mysql

rust-mysql-simple support library for the r2d2 connection pool. Documentation is available at http://outersky.github.io/r2d2-mysql/doc/v3.0.0/r2d2_mysql

Install

Just include another [dependencies] section into your Cargo.toml:

[dependencies]
r2d2_mysql="*"

Example

| ()).map_err(|err| { println!("execute query error in line:{} ! error: {:?}", line!(), err) }); }); tasks.push(th); } for th in tasks { let _ = th.join(); } }">
extern crate mysql;
extern crate r2d2_mysql;
extern crate r2d2;

use std::env;
use std::sync::Arc;
use std::thread;
use mysql::{Opts,OptsBuilder};
use mysql::prelude::Queryable;
use r2d2_mysql::MysqlConnectionManager;

fn main() {
	let url = env::var("DATABASE_URL").unwrap();
        let opts = Opts::from_url(&url).unwrap();
        let builder = OptsBuilder::from_opts(opts);
        let manager = MysqlConnectionManager::new(builder);
        let pool = Arc::new(r2d2::Pool::builder().max_size(4).build(manager).unwrap());

        let mut tasks = vec![];

        for _ in 0..3 {
            let pool = pool.clone();
            let th = thread::spawn(move || {
                let mut conn = pool.get()
                    .map_err(|err| {
                        println!(
                            "get connection from pool error in line:{} ! error: {:?}",
                            line!(),
                            err
                        )
                    })
                    .unwrap();
                let _ = conn.query("SELECT version()").map(|_: Vec<String>| ()).map_err(|err| {
                    println!("execute query error in line:{} ! error: {:?}", line!(), err)
                });
            });
            tasks.push(th);
        }

    for th in tasks {
        let _ = th.join();
    }
}
Comments
  • Compiler gives error on r2d2::Pool<r2d2_mysql::MysqlConnectionManager>

    Compiler gives error on r2d2::Pool

    Hi! I'm trying to compile code:

    struct Foo {
        pool: r2d2::Pool<r2d2_mysql::MysqlConnectionManager>,
    } 
    

    which gives me error

    src/main.rs:65:5: 65:39 error: the trait bound `r2d2_mysql::MysqlConnectionManager: r2d2::ManageConnection` is not satisfied [E0277]
    src/main.rs:65     pool: Pool<MysqlConnectionManager>,
                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    src/main.rs:65:5: 65:39 help: run `rustc --explain E0277` to see a detailed explanation
    src/main.rs:65:5: 65:39 note: required by `r2d2::Pool`
    

    My Cargo.toml

    [dependencies]
    mysql = "*"
    r2d2 = "*"
    r2d2_mysql = "*"
    rustc-serialize = "*"
    

    If I try to use https://github.com/sfackler/r2d2-postgres and replace code with

    struct Foo {
        pool: r2d2::Pool<r2d2_postgres::PostgresConnectionManager>,
    } 
    

    everything compiles. I can't see real differences in this two cargos. Both have

    impl r2d2::ManageConnection for PostgresConnectionManager {
    
    impl r2d2::ManageConnection for MysqlConnectionManager {
    

    I would appreciate any help. Thanks

    opened by shahmuratov 4
  • MySQL locking up the whole application when trying to run actions in a tokio spawn

    MySQL locking up the whole application when trying to run actions in a tokio spawn

    Hi,

    I'm pretty new to RUST, but I'm not understanding something. I've got a shared Pool which I initialize using a trait so that we can switch easly to MySQL or SQLite3 management. When using MySQL, I create a tokio spawn, in which it waits for a certain amount of time, to execute a Insert batch. When doing this insert batch, it seems like it's literally locking and freezing the rest of the application until it's done. What am I doing wrong here, do I need to use a different method to make sure the rest of the application keeps on going while a tokio spawn is doing it's work ?

    Explanation is appreciated, or examples how to avoid this.

    Kind regards.

    opened by Power2All 2
  • r2d2 mysql 8.0 can not work.

    r2d2 mysql 8.0 can not work.

    can see this example project. https://github.com/damody/r2d2mysql

    always get time out https://github.com/damody/r2d2mysql/blob/81e94cd757eea1c15f0342f7bd75593b32b5a0b9/src/main.rs#L71 and get error Commands out of sync; you can\'t run this command now

    opened by damody 1
  • Need new version published to Crates.io

    Need new version published to Crates.io

    Looking at the Cargo.toml, the repo marks this crate as version 9.0.0, yet the version that's known to Crates.io is only version 8.0.0. So any of the latest fixes (including my PR, #10) aren't available via the standard Cargo.toml inclusion.

    I'd like for you to upload a new version of the crate to Crates.io (cargo publish).

    Thanks!

    opened by ELD 1
  • update mysql dependency to 23

    update mysql dependency to 23

    • bump r2d2_mysql version to 23.0.0
    • rename MysqlConnectionManager => MySqlConnectionManager
      • this is more in line with mysql crate and rust conventions
    • add deprecated alias to old name for compatability
    • hide pool module since it provides no extra types
    • document public items
    opened by robjtede 0
  • clean up readme and example code

    clean up readme and example code

    • use more concise .expect error handling
    • combine imports
    • remove unnecessary extern crate statements
    • indicate where rows are accessible
    • return non-unit from query
    • rustfmt code
    • don't use "*" as version recommendation
    • point to docs.rs docs
    opened by robjtede 0
  • juniper::Executor does not support r2d2_mysql::MysqlConnectionManager

    juniper::Executor does not support r2d2_mysql::MysqlConnectionManager

    I would appreciate any help for the error below

    error

    error[E0277]: the trait bound `r2d2::PooledConnection<r2d2_mysql::MysqlConnectionManager>: diesel::Connection` is not satisfied
      --> src/graphql.rs:36:46
       |
    36 |             .load::<crate::models::Customer>(&executor.context().db_con)
       |                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `diesel::Connection` is not implemented for `r2d2::PooledConnection<r2d2_mysql::MysqlConnectionManager>`
       |
       = note: required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<r2d2::PooledConnection<r2d2_mysql::MysqlConnectionManager>, models::Customer>` for `schema::customers::table`
    
    error[E0277]: the trait bound `r2d2::PooledConnection<r2d2_mysql::MysqlConnectionManager>: diesel::Connection` is not satisfied
      --> src/graphql.rs:56:52
       |
    56 |             .get_result::<crate::models::Customer>(&executor.context().db_con)
       |                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^ the 
    

    dependencies

    actix-web = "1.0.9"
    actix-cors = "0.1.0"
    juniper = "0.14.1"
    juniper-from-schema = "0.5.1"
    juniper-eager-loading = "0.5.0"
    r2d2_mysql = "*"
    r2d2-diesel = "0.16.0"
    mysql = "*"
    r2d2 = "*"
    

    src/graphql.rs

    use std::convert::From;
    use std::sync::Arc;
    
    use actix_web::{web, Error, HttpResponse};
    use futures01::future::Future;
    
    use juniper::http::playground::playground_source;
    use juniper::{http::GraphQLRequest, Executor, FieldResult};
    use juniper_from_schema::graphql_schema_from_file;
    
    use diesel::prelude::*;
    
    use itertools::Itertools;
    
    use crate::{DbCon, DbPool};
    
    graphql_schema_from_file!("src/schema.graphql");
    
    pub struct Context {
        db_con: DbCon,
    }
    impl juniper::Context for Context {}
    
    pub struct Query;
    pub struct Mutation;
    
    impl QueryFields for Query {
        fn field_customers(
            &self,
            executor: &Executor<'_, Context>,
            _trail: &QueryTrail<'_, Customer, Walked>,
        ) -> FieldResult<Vec<Customer>> {
            use crate::schema::customers;
    
            customers::table
                .load::<crate::models::Customer>(&executor.context().db_con)
                .and_then(|customers| Ok(customers.into_iter().map_into().collect()))
                .map_err(Into::into)
        }
    }
    
    impl MutationFields for Mutation {
        fn field_create_customer(
            &self,
            executor: &Executor<'_, Context>,
            _trail: &QueryTrail<'_, Customer, Walked>,
            name: String,
            email: String,
        ) -> FieldResult<Customer> {
            use crate::schema::customers;
    
            let new_customer = crate::models::NewCustomer { name: &name, email: &email };
    
            diesel::insert_into(customers::table)
                .values(&new_customer)
                .get_result::<crate::models::Customer>(&executor.context().db_con)
                .map(Into::into)
                .map_err(Into::into)
        }
    }
    
    pub struct Customer {
        id: u64,
        name: String,
        email: String,
    }
    
    impl CustomerFields for Customer {
        fn field_id(&self, _: &Executor<'_, Context>) -> FieldResult<juniper::ID> {
            Ok(juniper::ID::new(self.id.to_string()))
        }
    
        fn field_name(&self, _: &Executor<'_, Context>) -> FieldResult<&String> {
            Ok(&self.name)
        }
        fn field_email(&self, _: &Executor<'_, Context>) -> FieldResult<&String> {
            Ok(&self.email)
        }
    }
    
    impl From<crate::models::Customer> for Customer {
        fn from(customer: crate::models::Customer) -> Self {
            Self {
                id: customer.id,
                name: customer.name,
                email: customer.email,
            }
        }
    }
    
    fn playground() -> HttpResponse {
        let html = playground_source("");
        HttpResponse::Ok()
            .content_type("text/html; charset=utf-8")
            .body(html)
    }
    
    fn graphql(
        schema: web::Data<Arc<Schema>>,
        data: web::Json<GraphQLRequest>,
        db_pool: web::Data<DbPool>,
    ) -> impl Future<Item = HttpResponse, Error = Error> {
        let ctx = Context {
            db_con: db_pool.get().unwrap(),
        };
    
        web::block(move || {
            let res = data.execute(&schema, &ctx);
            Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?)
        })
        .map_err(Error::from)
        .and_then(|customer| {
            Ok(HttpResponse::Ok()
                .content_type("application/json")
                .body(customer))
        })
    }
    
    pub fn register(config: &mut web::ServiceConfig) {
        let schema = std::sync::Arc::new(Schema::new(Query, Mutation));
    
        config
            .data(schema)
            .route("/", web::post().to_async(graphql))
            .route("/", web::get().to(playground));
    }
    

    src/main.rs

    #[macro_use]
    extern crate diesel;
    extern crate r2d2;
    use actix_cors::Cors;
    use actix_web::{web, App, HttpServer};
    
    use r2d2_mysql::mysql::{Opts, OptsBuilder};
    use r2d2_mysql::MysqlConnectionManager;
    
    use diesel::{
        prelude::*,
    };
    
    pub mod graphql;
    pub mod models;
    pub mod schema;
    
    pub type DbPool = r2d2::Pool<MysqlConnectionManager>;
    pub type DbCon = r2d2::PooledConnection<MysqlConnectionManager>;
    
    fn main() {
        let db_pool = create_db_pool();
        let port: u16 = std::env::var("PORT")
            .ok()
            .and_then(|p| p.parse().ok())
            .unwrap_or(8080);
    
        let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port));
    
        HttpServer::new(move || {
            App::new()
                .data(db_pool.clone())
                .wrap(Cors::new())
                .configure(graphql::register)
                .default_service(web::to(|| "404"))
        })
        .bind(addr)
        .unwrap()
        .run()
        .unwrap();
    }
    
    
    pub fn create_db_pool() -> DbPool {
        let db_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
        let opts = Opts::from_url(&db_url).unwrap();
        let builder = OptsBuilder::from_opts(opts);
        let manager = MysqlConnectionManager::new(builder);
        r2d2::Pool::new(manager).expect("Failed to create DB Pool")
    }
    
    opened by ryosuke-mitake 0
  • has_broken may block even though it should not.

    has_broken may block even though it should not.

    In the document about r2d2::ManageConnection.has_broken:

    This will be called synchronously every time a connection is returned to the pool, so it should not block.

    However r2d2_mysql::MysqlConnectionManager.has_broken may block when the network between the client and the server is in trouble.

    For example, an implementation might check if the underlying TCP socket has disconnected. Implementations that do not support this kind of fast health check may simply return false.

    Rust-mysql-simple doesn't support such kind of fast health check, so it may be better to simply return false.

    opened by kubo 0
  • Internal error occurred: Command

    Internal error occurred: Command "gcc.exe"

    error: failed to run custom build command for miniz-sys v0.1.11 process didn't exit successfully: D:\Rust\Rd2dTest\target\debug\build\miniz-sys-d13c924666e24cd6\build-script-build (exit code: 101) --- stdout TARGET = Some("x86_64-pc-windows-gnu") OPT_LEVEL = Some("0") HOST = Some("x86_64-pc-windows-gnu") CC_x86_64-pc-windows-gnu = None CC_x86_64_pc_windows_gnu = None HOST_CC = None CC = None CFLAGS_x86_64-pc-windows-gnu = None CFLAGS_x86_64_pc_windows_gnu = None HOST_CFLAGS = None CFLAGS = None CRATE_CC_NO_DEFAULTS = None DEBUG = Some("true") CARGO_CFG_TARGET_FEATURE = Some("fxsr,mmx,sse,sse2") running: "gcc.exe" "-O0" "-ffunction-sections" "-fdata-sections" "-g" "-fno-omit-frame-pointer" "-m64" "-DMINIZ_NO_STDIO" "-DMINIZ_NO_ARCHIVE_APIS" "-DMINIZ_NO_ARCHIVE_WRITING_APIS" "-DMINIZ_NO_TIME" "-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES" "-o" "D:\Rust\Rd2dTest\target\debug\build\miniz-sys-935e563594ae4ae2\out\miniz.o" "-c" "miniz.c" cargo:warning=cc1.exe: sorry, unimplemented: 64-bit mode not compiled in exit code: 1

    --- stderr thread 'main' panicked at '

    Internal error occurred: Command "gcc.exe" "-O0" "-ffunction-sections" "-fdata-sections" "-g" "-fno-omit-frame-pointer" "-m64" "-DMINIZ_NO_STDIO" "-DMINIZ_NO_ARCHIVE_APIS" "-DMINIZ_NO_ARCHIVE_WRITING_APIS" "-DMINIZ_NO_TIME" "-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES" "-o" "D:\Rust\Rd2dTest\target\debug\build\miniz-sys-935e563594ae4ae2\out\miniz.o" "-c" "miniz.c" with args "gcc.exe" did not execute successfully (status code exit code: 1).

    ', C:\Users\xiujie.zhu.cargo\registry\src\github.com-1ecc6299db9ec823\cc-1.0.35\src\lib.rs:2398:5 stack backtrace: 0: std::sys_common::backtrace::_print at src\libstd\sys\windows\backtrace/mod.rs:95 at src\libstd\sys\windows\backtrace/mod.rs:82 at src\libstd\sys_common/backtrace.rs:71 1: std::panicking::default_hook::{{closure}} at src\libstd\sys_common/backtrace.rs:59 at src\libstd/panicking.rs:197 2: std::panicking::default_hook at src\libstd/panicking.rs:211 3: std::panicking::rust_panic_with_hook at src\libstd/panicking.rs:474 4: std::panicking::continue_panic_fmt at src\libstd/panicking.rs:381 5: std::panicking::begin_panic_fmt at src\libstd/panicking.rs:336 6: cc::fail at C:\Users\xiujie.zhu.cargo\registry\src\github.com-1ecc6299db9ec823\cc-1.0.35\src/lib.rs:2398 7: cc::Build::compile at C:\Users\xiujie.zhu.cargo\registry\src\github.com-1ecc6299db9ec823\cc-1.0.35\src/lib.rs:951 8: build_script_build::main at .\build.rs:23 9: std::rt::lang_start::{{closure}} at /rustc/474e7a6486758ea6fc761893b1a49cd9076fb0ab\src\libstd/rt.rs:64 10: std::panicking::try::do_call at src\libstd/rt.rs:49 at src\libstd/panicking.rs:293 11: _rust_maybe_catch_panic at src\libpanic_unwind/lib.rs:87 12: std::rt::lang_start_internal at src\libstd/panicking.rs:272 at src\libstd/panic.rs:388 at src\libstd/rt.rs:48 13: std::rt::lang_start at /rustc/474e7a6486758ea6fc761893b1a49cd9076fb0ab\src\libstd/rt.rs:64 14: main 15: _tmainCRTStartup 16: mainCRTStartup 17: unit_addrs_search 18: unit_addrs_search

    opened by zhuxiujia 0
  • Bump mysql version, add test script

    Bump mysql version, add test script

    This commit updates the mysql version that this crate uses so it should compile without issue fixing #8. Additionally, it no longer assumes a root mysql user with a password and adds a test harness script that sets up and tears down the database used for testing.

    opened by ELD 0
Releases(v3.0.0)
Owner
outersky
a Java programmer since 1997
outersky
r2d2-cypher is a r2d2 connection pool for rusted-cypher

r2d2-cypher is a r2d2 connection pool for rusted-cypher

Markus Kohlhase 10 Oct 16, 2021
rust-postgres support library for the r2d2 connection pool

r2d2-postgres Documentation rust-postgres support library for the r2d2 connection pool. Example use std::thread; use r2d2_postgres::{postgres::NoTls,

Steven Fackler 128 Dec 26, 2022
Memcached support for the r2d2 connection pool (Rust)

Memcached support for the r2d2 connection pool (Rust)

川田 恵氏 (Kawada Keishi a.k.a megumish) 4 Jul 12, 2022
LDAP support for the r2d2 connection pool

r2d2-ldap LDAP support for the r2d2 connection pool Install Add this to your Cargo.toml: [dependencies] r2d2-ldap = "0.1.1" Basic Usage use std::threa

Aitor Ruano 2 Nov 7, 2020
Oracle support for the r2d2 connection pool

r2d2-oracle The documentation can be found on docs.rs. Oracle support for the r2d2 connection pool. This fits in between the r2d2 connection manager a

Ralph Ursprung 7 Dec 14, 2022
ODBC adapter for r2d2 connection pool

ODBC adapter for r2d2 connection pool

Konstantin V. Salikhov 9 Nov 3, 2021
Skytable rust client support library for the bb8 connection pool

bb8-skytable Skytable rust client support library for the bb8 connection pool. Heavily based on bb8-redis Basic usage example use bb8_skytable::{

null 3 Sep 18, 2021
A generic connection pool for Rust

r2d2 A generic connection pool for Rust. Documentation Opening a new database connection every time one is needed is both inefficient and can lead to

Steven Fackler 1.2k Jan 8, 2023
Quick Pool: High Performance Rust Async Resource Pool

Quick Pool High Performance Rust Async Resource Pool Usage DBCP Database Backend Adapter Version PostgreSQL tokio-postgres qp-postgres Example use asy

Seungjae Park 13 Aug 23, 2022
Mysql client library implemented in rust.

mysql This crate offers: MySql database driver in pure rust; connection pool. Features: macOS, Windows and Linux support; TLS support via nativetls cr

Anatoly I 548 Dec 31, 2022
🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, SQLite, and MSSQL.

SQLx ?? The Rust SQL Toolkit Install | Usage | Docs Built with ❤️ by The LaunchBadge team SQLx is an async, pure Rust† SQL crate featuring compile-tim

launchbadge 7.6k Dec 31, 2022
A highly scalable MySQL Proxy framework written in Rust

mysql-proxy-rs An implementation of a MySQL proxy server built on top of tokio-core. Overview This crate provides a MySQL proxy server that you can ex

AgilData 175 Dec 19, 2022
Asyncronous Rust Mysql driver based on Tokio.

mysql-async Tokio based asynchronous MySql client library for rust programming language. Installation Library hosted on crates.io. [dependencies] mysq

Anatoly I 292 Dec 30, 2022
A user crud written in Rust, designed to connect to a MySQL database with full integration test coverage.

SQLX User CRUD Purpose This application demonstrates the how to implement a common design for CRUDs in, potentially, a system of microservices. The de

null 78 Nov 27, 2022
cogo rust coroutine database driver (Mysql,Postgres,Sqlite)

cdbc Coroutine Database driver Connectivity.based on cogo High concurrency,based on coroutine No Future<'q,Output=*>,No async fn, No .await , no Poll*

co-rs 10 Nov 13, 2022
This project provides a Rust-based solution for migrating MSSQL databases to MySQL.

MSSQL to MySQL Database Migration A Rust project to migrate MSSQL databases to MySQL, including table structures, column data types, and table data ro

Bitalizer 2 Jul 10, 2023
A tool for automated migrations for PostgreSQL, SQLite and MySQL.

Models Models is an implementation for a SQL migration management tool. It supports PostgreSQL, MySQL, and SQLite. Quick Start install the CLI by runn

null 45 Nov 16, 2022
CRUD example with Rocket, Toql and MySQL

Todo (Rocket, Toql, MySQL) This is a little REST server built with Rocket, Toql and MySQL. The server allows to call CRUD functions on a Todo item. It

Artos 7 Jan 5, 2022
Gibbs MySQL Spyglass

Gibbs MySQL Spyglass Ahoy Matey! The Gibbs MySQL Spyglass is a application used to capture application traffic into a MySQL database. It is designed t

AgilData 82 Nov 14, 2021