Skip to content

Commit b2e180b

Browse files
committed
fix(PgSQL): Allow to pass IPv6 address in URI notation for postgres
Signed-off-by: Ferdinand Thiessen <[email protected]>
1 parent 9fca0ee commit b2e180b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

src/Driver/PgSQL/Driver.php

+10
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use function func_get_args;
1616
use function implode;
1717
use function pg_connect;
18+
use function preg_match;
1819
use function restore_error_handler;
1920
use function set_error_handler;
2021
use function sprintf;
@@ -64,9 +65,18 @@ private function constructConnectionString(
6465
#[SensitiveParameter]
6566
array $params
6667
): string {
68+
// pg_connect used by Doctrine DBAL does not support [...] notation,
69+
// but requires the host address in plain form like `aa:bb:99...`
70+
$matches = [];
71+
if (preg_match('/^\[(.+)\]$/', $params['host'] ?? '', $matches) === 1) {
72+
$params['hostaddr'] = $matches[1];
73+
unset($params['host']);
74+
}
75+
6776
$components = array_filter(
6877
[
6978
'host' => $params['host'] ?? null,
79+
'hostaddr' => $params['hostaddr'] ?? null,
7080
'port' => $params['port'] ?? null,
7181
'dbname' => $params['dbname'] ?? 'postgres',
7282
'user' => $params['user'] ?? null,

tests/Driver/PgSQL/DriverTest.php

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Doctrine\DBAL\Tests\Driver\PgSQL;
6+
7+
use Doctrine\DBAL\Driver as DriverInterface;
8+
use Doctrine\DBAL\Driver\PgSQL\Driver;
9+
use Doctrine\DBAL\Tests\Driver\AbstractPostgreSQLDriverTestCase;
10+
use Doctrine\DBAL\Tests\TestUtil;
11+
12+
class DriverTest extends AbstractPostgreSQLDriverTestCase
13+
{
14+
protected function setUp(): void
15+
{
16+
parent::setUp();
17+
18+
if (isset($GLOBALS['db_driver']) && $GLOBALS['db_driver'] === 'pgsql') {
19+
return;
20+
}
21+
22+
self::markTestSkipped('Test enabled only when using pgsql specific phpunit.xml');
23+
}
24+
25+
/**
26+
* Ensure we can handle URI notation for IPv6 addresses
27+
*/
28+
public function testConnectionIPv6(): void
29+
{
30+
$params = TestUtil::getConnectionParams();
31+
32+
if (!in_array($params['host'], ['localhost', '127.0.0.1', '[::1]'])) {
33+
// We cannot assume that every contributor runs the same setup as our CI
34+
self::markTestSkipped('This test only works if there is a Postgres server listening on localhost.');
35+
}
36+
37+
self::expectNotToPerformAssertions();
38+
39+
$params['host'] = '[::1]';
40+
$this->driver->connect($params);
41+
}
42+
43+
protected function createDriver(): DriverInterface
44+
{
45+
return new Driver();
46+
}
47+
}

0 commit comments

Comments
 (0)