1
0
mirror of https://github.com/danog/postgres.git synced 2024-11-27 04:24:45 +01:00
postgres/lib/PgSqlConnection.php

76 lines
2.4 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-05-17 18:14:12 +02:00
use Amp\{ Deferred, Failure, Loop, Promise };
2016-09-14 16:27:39 +02:00
class PgSqlConnection extends AbstractConnection {
/**
* @param string $connectionString
* @param int $timeout
2016-09-14 16:27:39 +02:00
*
* @return \Amp\Promise<\Amp\Postgres\PgSqlConnection>
2016-09-14 16:27:39 +02:00
*/
public static function connect(string $connectionString, int $timeout = 0): Promise {
2016-09-14 16:27:39 +02:00
if (!$connection = @\pg_connect($connectionString, \PGSQL_CONNECT_ASYNC | \PGSQL_CONNECT_FORCE_NEW)) {
return new Failure(new FailureException("Failed to create connection resource"));
2016-09-14 16:27:39 +02:00
}
2017-05-16 06:28:37 +02:00
2016-09-14 16:27:39 +02:00
if (\pg_connection_status($connection) === \PGSQL_CONNECTION_BAD) {
return new Failure(new FailureException(\pg_last_error($connection)));
2016-09-14 16:27:39 +02:00
}
2017-05-16 06:28:37 +02:00
2016-09-14 16:27:39 +02:00
if (!$socket = \pg_socket($connection)) {
return new Failure(new FailureException("Failed to access connection socket"));
2016-09-14 16:27:39 +02:00
}
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 ($watcher, $resource) use ($connection, $deferred) {
switch (\pg_connect_poll($connection)) {
case \PGSQL_POLLING_READING:
return; // Connection not ready, poll again.
case \PGSQL_POLLING_WRITING:
return; // Still writing...
case \PGSQL_POLLING_FAILED:
$deferred->fail(new FailureException("Could not connect to PostgreSQL server"));
return;
case \PGSQL_POLLING_OK:
$deferred->resolve(new self($connection, $resource));
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($socket, $callback);
$await = Loop::onWritable($socket, $callback);
$promise = $deferred->promise();
if ($timeout !== 0) {
$promise = Promise\timeout($promise, $timeout);
2016-09-14 16:27:39 +02:00
}
2017-03-22 01:16:25 +01:00
$promise->onResolve(function ($exception) use ($connection, $poll, $await) {
if ($exception) {
\pg_close($connection);
}
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 resource $handle PostgreSQL connection handle.
* @param resource $socket PostgreSQL connection stream socket.
*/
public function __construct($handle, $socket) {
parent::__construct(new PgSqlExecutor($handle, $socket));
}
}