sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

[MySQL] Fail to acquire new connection during the transaction

Open billy1624 opened this issue 5 years ago • 3 comments

After started the transaction I can no longer acquire new connection, until the transaction was finished. Is this an intentional behaviour? Thanks!!

let conn_pool: AnyPool = task::block_on(async {
    AnyPoolOptions::new()
        .max_connections(10)
        .connect_timeout(Duration::from_secs(3))
        .connect(&db_url)
        .await
        .unwrap()
})

Fail Case

let mut transaction = task::block_on(async {
    match conn_pool.begin().await {
        Err(e) => panic!(e),
        Ok(c) => c,
    }
});

... Insert & Update Actions

// ERROR: failed to get connection
let mut conn = match self.connection.conn_pool.try_acquire() {
    None => return Err("failed to get connection".into()),
    Some(c) => c,
};

Successful Case

let mut transaction = task::block_on(async {
    match conn_pool.begin().await {
        Err(e) => panic!(e),
        Ok(c) => c,
    }
});

... Insert & Update Actions

task::block_on(async {
    transaction.commit().await.unwrap();
});

// ERROR: failed to get connection
let mut conn = match self.connection.conn_pool.try_acquire() {
    None => return Err("failed to get connection".into()),
    Some(c) => c,
};

billy1624 avatar Nov 16 '20 05:11 billy1624

When you call connect it creates just 1 connection. When you begin a transaction - that acquires one connection from the pool it's not returned to the pool until transaction is committed. Therefore there is no more idle connections in the pool so try_acquire returns None.

If you want to create 10 connections, then specify min_connections in pool options. If you want to wait for additional connection to be opened (or become idle), then use acquire instead of try_acquire.

EDIT: Just realized it's an old issue. Anyway could be useful for someone who searches through issues.

stepantubanov avatar Feb 09 '24 14:02 stepantubanov

@billy1624 It would be great if you had these changes since we have these problems very often

efrain2007 avatar Mar 13 '24 18:03 efrain2007

Was there any solution to this problem?

efrain2007 avatar Mar 13 '24 23:03 efrain2007