From 0ec46e17cc970bc8332b2aa268ba1b41fbc948e6 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 25 Nov 2019 23:08:33 +0100 Subject: [PATCH] Default to real-utf8 when no charset is provided --- ConnectionFactory.php | 15 +++++++++++++++ Tests/ConnectionFactoryTest.php | 20 ++++++++++++++++++++ UPGRADE-2.0.md | 2 ++ 3 files changed, 37 insertions(+) diff --git a/ConnectionFactory.php b/ConnectionFactory.php index 4fb04b2e6..08e96d0aa 100644 --- a/ConnectionFactory.php +++ b/ConnectionFactory.php @@ -6,6 +6,7 @@ use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DBALException; +use Doctrine\DBAL\Driver\AbstractMySQLDriver; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Exception\DriverException; use Doctrine\DBAL\Platforms\AbstractPlatform; @@ -43,6 +44,20 @@ public function createConnection(array $params, Configuration $config = null, Ev $connection = DriverManager::getConnection($params, $config, $eventManager); + if (!isset($params['pdo']) && !isset($params['charset'])) { + $params = $connection->getParams(); + $params['charset'] = 'utf8'; + $driver = $connection->getDriver(); + + if ($driver instanceof AbstractMySQLDriver) { + $params['charset'] = 'utf8mb4'; + $params['defaultTableOptions']['collate'] = $params['defaultTableOptions']['collate'] ?? 'utf8mb4_unicode_ci'; + } + + $connectionClass = \get_class($connection); + $connection = new $connectionClass($params, $driver, $connection->getConfiguration(), $connection->getEventManager()); + } + if (! empty($mappingTypes)) { $platform = $this->getDatabasePlatform($connection); foreach ($mappingTypes as $dbType => $doctrineType) { diff --git a/Tests/ConnectionFactoryTest.php b/Tests/ConnectionFactoryTest.php index d82bed875..7cbe6a5a5 100644 --- a/Tests/ConnectionFactoryTest.php +++ b/Tests/ConnectionFactoryTest.php @@ -49,6 +49,26 @@ public function testContainer() FakeDriver::$exception = null; } } + + public function testDefaultCharset() + { + $factory = new ConnectionFactory([]); + $params = ['driverClass' => FakeDriver::class]; + + $connection = $factory->createConnection($params); + + $this->assertSame('utf8', $connection->getParams()['charset']); + } + + public function testDefaultCharsetMySql() + { + $factory = new ConnectionFactory([]); + $params = ['driver' => 'pdo_mysql']; + + $connection = $factory->createConnection($params); + + $this->assertSame('utf8mb4', $connection->getParams()['charset']); + } } /** diff --git a/UPGRADE-2.0.md b/UPGRADE-2.0.md index 1ca22a062..82aee80a0 100644 --- a/UPGRADE-2.0.md +++ b/UPGRADE-2.0.md @@ -9,6 +9,8 @@ PHP and Symfony version support Symfony 3.4 LTS and 4.1 or newer. * Support for Twig 1.34 and below as well as 2.4 and below (for 2.x) releases was dropped. + * When no charset parameter is defined, it now defaults to `utf8mb4` on the + MySQL platform and to `utf8` on all other platforms. Commands --------