AsyncMysqlClient::adoptConnection

Create a new async connection from a synchronous MySQL instance.

Description

public static function adoptConnection(
  $connection,
): AsyncMysqlConnection

Create a new async connection from a synchronous MySQL instance.

This is a synchronous function. You will block until the connection has been adopted to an AsyncMysqlConnection. Then you will be able to use the async AsyncMysqlConnection methods like queryf(), etc.

This is a tricky function to use and we are actually thinking of deprecating it. This function requires a deprecated, MySQL resource. Once this resource is adopted by a call to this function, it is no longer valid in the context on which it was being used.

If you are using this function, you might consider just creating a connection pool via AsyncMysqlConnectionPool since you presumably have all the connection details anyway.

Parameters

  • $connection - The synchronous MySQL connection.

Return Values

Examples

This example shows how to take a synchronous MySQL connection and convert it to use an asynchronous MySQL connection via AsyncMysqlClient::adoptConnection().

NOTE: Right now this does not work with mysqli or PDO connections.

<?hh

namespace Hack\UserDocumentation\API\Examples\AsyncMysql\Client\AdoptConn;

use \Hack\UserDocumentation\API\Examples\AsyncMysql\ConnectionInfo as CI;

function get_synchronous_connection(): resource {
  $conn = mysql_connect(
    CI::$host,
    CI::$user,
    CI::$passwd
  );
  mysql_select_db(
    CI::$db,
    $conn
  );
  return $conn;
}

function use_async_connection(resource $sync_conn): \AsyncMysqlConnection {
  return \AsyncMysqlClient::adoptConnection($sync_conn);
}

async function get_rows(\AsyncMysqlConnection $conn):
  Awaitable<\AsyncMysqlQueryResult> {
  return await $conn->query('SELECT * FROM test_table');
}

function run_it(): void {
  $sconn = get_synchronous_connection();
  $aconn = use_async_connection($sconn);
  $rows = \HH\Asio\join(get_rows($aconn));
  var_dump($rows->numRows()); // The number of rows from the SELECT statement
}

run_it();
Output
int(30)