Created
May 14, 2014 11:11
-
-
Save Petah/74a4fdac695244aa2da4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class MySQLiAsyncQuery { | |
| public $mysqli; | |
| public $query; | |
| public $links; | |
| public $errors; | |
| public $reject; | |
| public $mysqlnd; | |
| public $result; | |
| public $kill_connection; | |
| public $thread_id; | |
| public function __construct($mysqli, $query) { | |
| $this->mysqli = $mysqli; | |
| $this->query = $query; | |
| // Check for mysqlnd | |
| $this->mysqlnd = \function_exists('mysqli_fetch_all'); | |
| if ($this->mysqlnd) { | |
| $this->kill_connection = $this->mysqli->aconnect(); | |
| $this->mysqli->mysqli->query($query, MYSQLI_ASYNC); | |
| $this->thread_id = $this->mysqli->mysqli->thread_id; | |
| } else { | |
| $this->result = $this->mysqli->mysqli->query($query); | |
| } | |
| } | |
| public function poll($time = 500000) { | |
| if (!$this->mysqlnd) return 1; | |
| $this->links = $this->errors = $this->reject = array($this->mysqli->mysqli); | |
| return mysqli_poll($this->links, $this->errors, $this->reject, 0, $time); | |
| } | |
| public function kill() { | |
| if (!$this->mysqlnd) return 1; | |
| return mysqli_kill($this->kill_connection, $this->thread_id); | |
| } | |
| public function wait_kill($time = 500000, $flush = true) { | |
| if (!$this->mysqlnd) return $this; | |
| $ignore = ignore_user_abort(true); | |
| while (!$this->poll($time)) { | |
| if (connection_aborted() && $result->kill()) { | |
| die(); | |
| } | |
| if ($flush === true) { | |
| // Flush some data to check for aborted connection | |
| echo str_repeat(PHP_EOL, 512); | |
| flush(); | |
| } | |
| } | |
| ignore_user_abort($ignore); | |
| return $this; | |
| } | |
| public function result() { | |
| if (!$this->mysqlnd) return $this->result; | |
| foreach ($this->links as $link) { | |
| if ($result = $link->reap_async_query()) { | |
| return $result; | |
| } | |
| } | |
| return false; | |
| } | |
| public function is_error() { | |
| return mysqli_errno($this->mysqli->mysqli) != 0; | |
| } | |
| public function errno() { | |
| return mysqli_errno($this->mysqli->mysqli); | |
| } | |
| public function error() { | |
| return mysqli_error($this->mysqli->mysqli); | |
| } | |
| public function throw_error() { | |
| if ($this->is_error()) { | |
| throw new MySQLiDatabaseException('Could not query database: '.$this->query, $this->errno(), $this->error()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment