Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Alternative database port in Postgres DSN #46403

Merged
merged 2 commits into from Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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