void AsyncConnectionPool::recycleMysqlConnection()

in squangle/mysql_client/AsyncConnectionPool.cpp [240:283]


void AsyncConnectionPool::recycleMysqlConnection(
    std::unique_ptr<MysqlConnectionHolder> mysql_conn) {
  // this method can run by any thread where the Connection is dying
  {
    std::unique_lock<std::mutex> lock(shutdown_mutex_);
    if (shutting_down_) {
      return;
    }
  }
  VLOG(2) << "Trying to recycle connection";

  if (!mysql_conn->isReusable()) {
    return;
  }

  // Check server_status for in_transaction bit
  if (mysql_conn->inTransaction()) {
    // To avoid complication, we are just going to close the connection
    LOG_EVERY_N(INFO, 1000) << "Closing connection during a transaction."
                            << " Transaction will rollback.";
    return;
  }

  auto pool = getSelfWeakPointer();
  auto pmysql_conn = mysql_conn.release();
  bool scheduled = mysql_client_->runInThread([pool, pmysql_conn]() {
    std::unique_ptr<MysqlPooledHolder> mysql_connection(
        static_cast<MysqlPooledHolder*>(pmysql_conn));
    auto shared_pool = pool.lock();
    if (!shared_pool) {
      return;
    }

    // in mysql 5.7 we can use mysql_reset_connection
    // We don't have a nonblocking version for reset connection, so we
    // are going to delete the old one and the open connection being
    // removed procedure is going to check if it needs to open new one
    shared_pool->addConnection(std::move(mysql_connection), false);
  });

  if (!scheduled) {
    delete pmysql_conn;
  }
}