Skip to content

Commit

Permalink
[10.x] Alternative database port in Postgres DSN (#46403)
Browse files Browse the repository at this point in the history
* feat: add support for Postgres connect_via_database port definition

* test: add pgsql connect_via_port test
  • Loading branch information
timvango committed Mar 9, 2023
1 parent 7f57a54 commit e7e9f36
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Connectors/PostgresConnector.php
Expand Up @@ -167,13 +167,14 @@ protected function getDsn(array $config)
// name than the database used for "information_schema" queries. This is
// typically the case if using "pgbouncer" type software when pooling.
$database = $connect_via_database ?? $database;
$port = $connect_via_port ?? $port ?? null;

$dsn = "pgsql:{$host}dbname='{$database}'";

// If a port was specified, we will add it to this Postgres DSN connections
// format. Once we have done that we are ready to return this connection
// string back out for usage, as this has been fully constructed here.
if (isset($config['port'])) {
if ($port !== null) {
$dsn .= ";port={$port}";
}

Expand Down
16 changes: 16 additions & 0 deletions tests/Database/DatabaseConnectorTest.php
Expand Up @@ -232,6 +232,22 @@ public function testPostgresApplicationUseAlternativeDatabaseName()
$this->assertSame($result, $connection);
}

public function testPostgresApplicationUseAlternativeDatabaseNameAndPort()
{
$dsn = 'pgsql:dbname=\'baz\';port=2345';
$config = ['database' => 'bar', 'connect_via_database' => 'baz', 'port' => 5432, 'connect_via_port' => 2345];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
$connection = m::mock(stdClass::class);
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
$statement = m::mock(PDOStatement::class);
$connection->shouldReceive('prepare')->zeroOrMoreTimes()->andReturn($statement);
$statement->shouldReceive('execute')->zeroOrMoreTimes();
$result = $connector->connect($config);

$this->assertSame($result, $connection);
}

public function testPostgresConnectorReadsIsolationLevelFromConfig()
{
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111';
Expand Down

0 comments on commit e7e9f36

Please sign in to comment.