Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,17 @@ class PostgreSQLDatabaseManager extends TenantDatabaseManager
{
public function createDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("CREATE DATABASE \"{$tenant->database()->getName()}\" WITH TEMPLATE=template0");
$database = $tenant->database()->getName();
// If null, Postgres creates the DB with the server's default charset
$charset = $this->connection()->getConfig('charset');

$query = "CREATE DATABASE \"{$database}\" WITH TEMPLATE=template0";

if ($charset !== null) {
$query .= " ENCODING='" . strtoupper($charset) . "'";
}

return $this->connection()->statement($query);
}

public function deleteDatabase(TenantWithDatabase $tenant): bool
Expand Down
37 changes: 37 additions & 0 deletions tests/TenantDatabaseManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,43 @@
expect($manager->connection()->getConfig('url'))->toBeNull();
});

test('newly created postgres databases use the correct charset', function (string|null $charset) {
config([
'tenancy.database.managers.pgsql' => PostgreSQLDatabaseManager::class,
'database.connections.pgsql.charset' => $charset, // If null, Postgres creates the DB with the server's default charset
]);

// Purge connection to make sure the updated charset config is used
DB::purge('pgsql');

Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant;
})->toListener());

$tenant = Tenant::create([
'tenancy_db_connection' => 'pgsql',
]);

$databaseName = $tenant->database()->getName();

// Postgres server's default charset
$serverCharset = DB::connection('pgsql')
->selectOne("SELECT pg_encoding_to_char(encoding) AS encoding FROM pg_database WHERE datname = 'template1'")
->encoding;

// Charset of the newly created tenant database
$dbCharset = DB::connection('pgsql')
->selectOne('SELECT pg_encoding_to_char(encoding) AS encoding FROM pg_database WHERE datname = ?', [$databaseName])
->encoding;

$expectedCharset = $charset !== null ? strtoupper($charset) : $serverCharset;

expect($dbCharset)->toBe($expectedCharset);
})->with([
null,
'utf8',
]);

// Datasets
dataset('database_managers', [
['mysql', MySQLDatabaseManager::class],
Expand Down
Loading