Skip to content
This repository was archived by the owner on Sep 28, 2022. It is now read-only.

Commit 01b061b

Browse files
authored
Fix connect() (#66)
* Fix reconnect after connect failed * Add timeout param in connect()
1 parent 6f60324 commit 01b061b

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

swoole_postgresql.cc

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -342,9 +342,12 @@ static PHP_METHOD(swoole_postgresql_coro, __construct) {}
342342

343343
static PHP_METHOD(swoole_postgresql_coro, connect) {
344344
zval *conninfo;
345+
double timeout = Socket::default_connect_timeout;
345346

346-
ZEND_PARSE_PARAMETERS_START(1, 1)
347+
ZEND_PARSE_PARAMETERS_START(1, 2)
347348
Z_PARAM_ZVAL(conninfo)
349+
Z_PARAM_OPTIONAL
350+
Z_PARAM_DOUBLE(timeout)
348351
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
349352

350353
PGObject *object = php_swoole_postgresql_coro_get_object(ZEND_THIS);
@@ -385,6 +388,12 @@ static PHP_METHOD(swoole_postgresql_coro, connect) {
385388
object->status = CONNECTION_STARTED;
386389
object->connected = false;
387390

391+
ON_SCOPE_EXIT {
392+
if (!object->connected) {
393+
object->conn = NULL;
394+
}
395+
};
396+
388397
PQsetnonblocking(pgsql, 1);
389398
PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, object);
390399

@@ -396,7 +405,7 @@ static PHP_METHOD(swoole_postgresql_coro, connect) {
396405
RETURN_FALSE;
397406
}
398407

399-
if (!object->yield(return_value, SW_EVENT_WRITE, Socket::default_connect_timeout)) {
408+
if (!object->yield(return_value, SW_EVENT_WRITE, timeout)) {
400409
const char *feedback;
401410

402411
switch (PQstatus(pgsql)) {

tests/unit/PostgreSQLTest.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ class PostgreSQLTest extends TestCase
99
protected function getConn()
1010
{
1111
$pg = new Swoole\Coroutine\PostgreSQL();
12-
$conn = $pg->connect(TEST_DB_URI);
12+
$conn = $pg->connect(TEST_DB_URI, 5);
1313
$this->assertNotFalse($conn, (string) $pg->error);
1414

1515
return $pg;
@@ -90,4 +90,14 @@ public function testNotConnected()
9090
$this->assertFalse($pg->metaData(''));
9191
});
9292
}
93+
94+
public function testConnectFailed()
95+
{
96+
run(function () {
97+
$pg = new Swoole\Coroutine\PostgreSQL();
98+
$this->assertFalse($pg->connect(''));
99+
$conn = $pg->connect(TEST_DB_URI);
100+
$this->assertNotFalse($conn, (string) $pg->error);
101+
});
102+
}
93103
}

0 commit comments

Comments
 (0)