Guest User

Untitled

a guest
Dec 24th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. <?php
  2.  
  3. use function Amp\call;
  4. use Amp\Mysql\CommandResult;
  5. use Amp\Mysql\ConnectionException;
  6. use Amp\Mysql\InitializationException;
  7. use Amp\Mysql\QueryError;
  8. use Amp\Mysql\ResultSet;
  9. use Amp\Promise;
  10. use Amp\Socket\ConnectException;
  11.  
  12. function query(\Amp\Mysql\Pool $pool, string $query): Promise
  13. {
  14. return call(function () use ($query, $pool) {
  15. $tryAgain = true;
  16. while (true) {
  17. echo "Try\n";
  18. /**
  19. * @var \Sensphere\DB\MySql\Connection $connection
  20. */
  21. try {
  22. /**
  23. * @var ResultSet $result
  24. */
  25. $result = yield $pool->query($query);
  26.  
  27. if ($result instanceof CommandResult) {
  28. return new \Sensphere\DB\Async\Result(
  29. null,
  30. $result->affectedRows()
  31. );
  32. }
  33.  
  34. echo "Got response\n";
  35.  
  36. /**
  37. * @var ResultSet $result
  38. */
  39. $rows = [];
  40. while (yield $result->advance()) {
  41. $rows[] = $result->getCurrent();
  42. }
  43.  
  44. echo "Resolve\n";
  45. return $rows;
  46. } catch (ConnectException | InitializationException | ConnectionException $e) {
  47. // Always retry if server went away. It maybe necessary to retry multiple times if there are multiple idle connections in the pool
  48. if (strpos($e->getMessage(), 'went away') !== false) {
  49. echo "MySQL went away on query $query\n";
  50. $tryAgain = true;
  51. }
  52.  
  53. // Retry once on connect errors
  54. if ($tryAgain) {
  55. $tryAgain = false;
  56. continue;
  57. }
  58.  
  59. throw new Exception($e->getMessage(), $e->getCode(), $e);
  60. } catch (QueryError $e) {
  61. throw new Exception('query error ("' . $message . '"), query "' . $e->getQuery() . '", ' . $this->schema, $code);
  62. }
  63. }
  64. });
  65. }
  66.  
  67. \Amp\Loop::run(function () {
  68. $pool = \Amp\Mysql\pool("user=...;host=...;pass=...;db=...", null, 10);
  69. yield query($pool, "SET wait_timeout = 1");
  70. yield new \Amp\Delayed(2000);
  71. $sql = "SELECT ...";
  72. yield query($pool, $sql);
  73. echo "DONE\n";
  74. });
Add Comment
Please, Sign In to add comment