Skip to content

Commit dc9af65

Browse files
[9.x] Alternative database name in Postgres DSN, allow pgbouncer aliased 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>
1 parent dfeac8c commit dc9af65

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/Illuminate/Database/Connectors/PostgresConnector.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,11 @@ protected function getDsn(array $config)
163163

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

166+
// Sometimes - users may need to connect to a database that has a different
167+
// name than the database used for "information_schema" queries. This is
168+
// typically the case if using "pgbouncer" type software when pooling.
169+
$database = $connect_via_database ?? $database;
170+
166171
$dsn = "pgsql:{$host}dbname='{$database}'";
167172

168173
// If a port was specified, we will add it to this Postgres DSN connections

tests/Database/DatabaseConnectorTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,22 @@ public function testPostgresApplicationNameIsSet()
216216
$this->assertSame($result, $connection);
217217
}
218218

219+
public function testPostgresApplicationUseAlternativeDatabaseName()
220+
{
221+
$dsn = 'pgsql:dbname=\'baz\'';
222+
$config = ['database' => 'bar', 'connect_via_database' => 'baz'];
223+
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
224+
$connection = m::mock(stdClass::class);
225+
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
226+
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
227+
$statement = m::mock(PDOStatement::class);
228+
$connection->shouldReceive('prepare')->zeroOrMoreTimes()->andReturn($statement);
229+
$statement->shouldReceive('execute')->zeroOrMoreTimes();
230+
$result = $connector->connect($config);
231+
232+
$this->assertSame($result, $connection);
233+
}
234+
219235
public function testPostgresConnectorReadsIsolationLevelFromConfig()
220236
{
221237
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111';

0 commit comments

Comments
 (0)