Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use function Amp\call;
- use Amp\Mysql\CommandResult;
- use Amp\Mysql\ConnectionException;
- use Amp\Mysql\InitializationException;
- use Amp\Mysql\QueryError;
- use Amp\Mysql\ResultSet;
- use Amp\Promise;
- use Amp\Socket\ConnectException;
- function query(\Amp\Mysql\Pool $pool, string $query): Promise
- {
- return call(function () use ($query, $pool) {
- $tryAgain = true;
- while (true) {
- echo "Try\n";
- /**
- * @var \Sensphere\DB\MySql\Connection $connection
- */
- try {
- /**
- * @var ResultSet $result
- */
- $result = yield $pool->query($query);
- if ($result instanceof CommandResult) {
- return new \Sensphere\DB\Async\Result(
- null,
- $result->affectedRows()
- );
- }
- echo "Got response\n";
- /**
- * @var ResultSet $result
- */
- $rows = [];
- while (yield $result->advance()) {
- $rows[] = $result->getCurrent();
- }
- echo "Resolve\n";
- return $rows;
- } catch (ConnectException | InitializationException | ConnectionException $e) {
- // Always retry if server went away. It maybe necessary to retry multiple times if there are multiple idle connections in the pool
- if (strpos($e->getMessage(), 'went away') !== false) {
- echo "MySQL went away on query $query\n";
- $tryAgain = true;
- }
- // Retry once on connect errors
- if ($tryAgain) {
- $tryAgain = false;
- continue;
- }
- throw new Exception($e->getMessage(), $e->getCode(), $e);
- } catch (QueryError $e) {
- throw new Exception('query error ("' . $message . '"), query "' . $e->getQuery() . '", ' . $this->schema, $code);
- }
- }
- });
- }
- \Amp\Loop::run(function () {
- $pool = \Amp\Mysql\pool("user=...;host=...;pass=...;db=...", null, 10);
- yield query($pool, "SET wait_timeout = 1");
- yield new \Amp\Delayed(2000);
- $sql = "SELECT ...";
- yield query($pool, $sql);
- echo "DONE\n";
- });
Add Comment
Please, Sign In to add comment