2016-12-30 06:21:17 +01:00
|
|
|
<?php
|
2016-09-14 16:27:39 +02:00
|
|
|
|
|
|
|
namespace Amp\Postgres;
|
|
|
|
|
2017-02-16 00:36:10 +01:00
|
|
|
use Amp\{ Deferred, Failure };
|
2017-01-18 18:05:05 +01:00
|
|
|
use AsyncInterop\{ Loop, Promise };
|
2016-09-14 16:27:39 +02:00
|
|
|
use pq;
|
|
|
|
|
|
|
|
class PqConnection extends AbstractConnection {
|
|
|
|
/**
|
|
|
|
* @param string $connectionString
|
2017-02-16 00:36:10 +01:00
|
|
|
* @param int $timeout
|
2016-09-14 16:27:39 +02:00
|
|
|
*
|
2017-01-18 18:05:05 +01:00
|
|
|
* @return \AsyncInterop\Promise<\Amp\Postgres\PgSqlConnection>
|
2016-09-14 16:27:39 +02:00
|
|
|
*/
|
2017-02-16 00:36:10 +01:00
|
|
|
public static function connect(string $connectionString, int $timeout = 0): Promise {
|
2016-09-14 16:27:39 +02:00
|
|
|
try {
|
|
|
|
$connection = new pq\Connection($connectionString, pq\Connection::ASYNC);
|
|
|
|
} catch (pq\Exception $exception) {
|
2017-02-16 00:36:10 +01:00
|
|
|
return new Failure(new FailureException("Could not connect to PostgresSQL server", 0, $exception));
|
2016-09-14 16:27:39 +02:00
|
|
|
}
|
|
|
|
$connection->resetAsync();
|
|
|
|
$connection->nonblocking = true;
|
|
|
|
$connection->unbuffered = true;
|
|
|
|
|
|
|
|
$deferred = new Deferred;
|
|
|
|
|
2017-02-16 00:36:10 +01:00
|
|
|
$callback = function () use ($connection, $deferred) {
|
|
|
|
switch ($connection->poll()) {
|
|
|
|
case pq\Connection::POLLING_READING:
|
|
|
|
return; // Connection not ready, poll again.
|
|
|
|
|
|
|
|
case pq\Connection::POLLING_WRITING:
|
|
|
|
return; // Still writing...
|
|
|
|
|
|
|
|
case pq\Connection::POLLING_FAILED:
|
|
|
|
$deferred->fail(new FailureException("Could not connect to PostgreSQL server"));
|
|
|
|
return;
|
|
|
|
|
|
|
|
case pq\Connection::POLLING_OK:
|
|
|
|
case \PGSQL_POLLING_OK:
|
|
|
|
$deferred->resolve(new self($connection));
|
|
|
|
return;
|
2016-09-14 16:27:39 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
$poll = Loop::onReadable($connection->socket, $callback);
|
|
|
|
$await = Loop::onWritable($connection->socket, $callback);
|
2017-02-16 00:36:10 +01:00
|
|
|
|
|
|
|
$promise = $deferred->promise();
|
|
|
|
|
|
|
|
if ($timeout !== 0) {
|
|
|
|
$promise = \Amp\timeout($promise, $timeout);
|
2016-09-14 16:27:39 +02:00
|
|
|
}
|
2017-02-16 00:36:10 +01:00
|
|
|
|
|
|
|
$promise->when(function () use ($poll, $await) {
|
|
|
|
Loop::cancel($poll);
|
|
|
|
Loop::cancel($await);
|
|
|
|
});
|
|
|
|
|
|
|
|
return $promise;
|
2016-09-14 16:27:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param \pq\Connection $handle
|
|
|
|
*/
|
|
|
|
public function __construct(pq\Connection $handle) {
|
|
|
|
parent::__construct(new PqExecutor($handle));
|
|
|
|
}
|
|
|
|
}
|