Hi, I am trying mysql_async
with warp
something like this:
The pool:
let mut opts = mysql_async::OptsBuilder::new();
opts.user(dsn.username);
opts.pass(dsn.password.clone());
opts.ip_or_hostname(dsn.host.unwrap());
opts.socket(dsn.socket);
opts.db_name(dsn.database);
if let Some(port) = dsn.port {
opts.tcp_port(port);
}
opts.pool_options(mysql_async::PoolOptions::with_constraints(
mysql_async::PoolConstraints::new(10, 100).unwrap(),
));
// mysql ssl options
let mut ssl_opts = mysql_async::SslOpts::default();
if let Some(tls) = dsn.params.get("tls") {
if *tls == "skip-verify" {
ssl_opts.set_danger_accept_invalid_certs(true);
}
}
opts.ssl_opts(ssl_opts);
mysql_async::Pool::new(opts)
Then with warp:
let pool = options::new();
pool.get_conn().await.unwrap_or_else(|e| {
eprintln!("Could not connect to MySQL: {}", e);
process::exit(1);
});
println!("{:#?}", pool);
let db = warp::any().map(move || pool.clone());
let register = warp::post()
.and(warp::path("register"))
.and(warp::body::json())
.and(db.clone())
.and_then(register);
warp::serve(register).run(([0, 0, 0, 0], 8000)).await;
async fn register(
user: User,
pool: mysql_async::Pool,
) -> Result<impl warp::Reply, warp::Rejection> {
match queries::find_user(pool.clone(), &user.username, &user.email).await {
Ok(rs) => {
println!("{:?}", rs);
Ok(StatusCode::CREATED)
}
err => {
eprintln!("{:?}", err);
Ok(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
and queries is something like:
pub async fn find_user(
pool: mysql_async::Pool,
username: &str,
email: &str,
) -> Result<usize, Box<dyn Error>> {
let conn = pool.get_conn().await?;
let (_, row) = conn
.first_exec::<_,_,usize>(
"SELECT IF((SELECT count(*) FROM users WHERE email=?), 2, (IF((SELECT count(*) FROM users WHERE name=?), 1, 0)))",
(&email, &username),
).await?;
Ok(row.ok_or("expecting a row")?)
}
It works but in some cases, I am getting an Err(Driver(ConnectionClosed))
, also the pool is always one connection instead of 10 as defined, therefore wondering what could be wrong or if I should close the connection after every use.
Any ideas?