Skip to content

Commit

Permalink
[9.x] Alternative database name in Postgres DSN, allow pgbouncer alia…
Browse files Browse the repository at this point in the history
…sed databases to continue working on 9.x (#43542)

* feat: allow creating a Postgres DSN string with a different database name than is used for information_schema queries

See #43536

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
AlbinoDrought and taylorotwell committed Aug 4, 2022
1 parent dfeac8c commit dc9af65
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Illuminate/Database/Connectors/PostgresConnector.php
Expand Up @@ -163,6 +163,11 @@ protected function getDsn(array $config)

$host = isset($host) ? "host={$host};" : '';

// Sometimes - users may need to connect to a database that has a different
// 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;

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

// If a port was specified, we will add it to this Postgres DSN connections
Expand Down
16 changes: 16 additions & 0 deletions tests/Database/DatabaseConnectorTest.php
Expand Up @@ -216,6 +216,22 @@ public function testPostgresApplicationNameIsSet()
$this->assertSame($result, $connection);
}

public function testPostgresApplicationUseAlternativeDatabaseName()
{
$dsn = 'pgsql:dbname=\'baz\'';
$config = ['database' => 'bar', 'connect_via_database' => 'baz'];
$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 dc9af65

Please sign in to comment.