1
0
mirror of https://github.com/danog/postgres.git synced 2024-12-13 18:07:31 +01:00
postgres/lib/PqConnection.php

69 lines
2.2 KiB
PHP
Raw Normal View History

2016-12-30 06:21:17 +01:00
<?php
2016-09-14 16:27:39 +02:00
namespace Amp\Postgres;
2017-06-05 06:42:18 +02:00
use Amp\{ CancellationToken, Deferred, Failure, Loop, NullCancellationToken, Promise };
2016-09-14 16:27:39 +02:00
use pq;
class PqConnection extends AbstractConnection {
/**
* @param string $connectionString
2017-06-05 06:42:18 +02:00
* @param \Amp\CancellationToken $token
2016-09-14 16:27:39 +02:00
*
* @return \Amp\Promise<\Amp\Postgres\PgSqlConnection>
2016-09-14 16:27:39 +02:00
*/
2017-06-05 06:42:18 +02:00
public static function connect(string $connectionString, CancellationToken $token = null): Promise {
2016-09-14 16:27:39 +02:00
try {
$connection = new pq\Connection($connectionString, pq\Connection::ASYNC);
} catch (pq\Exception $exception) {
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;
2017-05-16 06:28:37 +02:00
2016-09-14 16:27:39 +02:00
$deferred = new Deferred;
2017-05-16 06:28:37 +02: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:
2017-06-05 06:42:18 +02:00
$deferred->fail(new FailureException($connection->errorMessage));
return;
case pq\Connection::POLLING_OK:
$deferred->resolve(new self($connection));
return;
2016-09-14 16:27:39 +02:00
}
};
2017-05-16 06:28:37 +02:00
2016-09-14 16:27:39 +02:00
$poll = Loop::onReadable($connection->socket, $callback);
$await = Loop::onWritable($connection->socket, $callback);
$promise = $deferred->promise();
2017-06-05 06:42:18 +02:00
$token = $token ?? new NullCancellationToken;
$id = $token->subscribe([$deferred, "fail"]);
2017-06-05 06:42:18 +02:00
$promise->onResolve(function () use ($poll, $await, $id, $token) {
$token->unsubscribe($id);
Loop::cancel($poll);
Loop::cancel($await);
});
return $promise;
2016-09-14 16:27:39 +02:00
}
2017-05-16 06:28:37 +02:00
2016-09-14 16:27:39 +02:00
/**
* @param \pq\Connection $handle
*/
public function __construct(pq\Connection $handle) {
parent::__construct(new PqExecutor($handle));
}
}