diff --git a/src/Db/Adapter/MysqlAdapter.php b/src/Db/Adapter/MysqlAdapter.php index 9f5d43c8..3bf1aa3a 100644 --- a/src/Db/Adapter/MysqlAdapter.php +++ b/src/Db/Adapter/MysqlAdapter.php @@ -107,7 +107,7 @@ public function connect(): void */ public function setConnection(Connection $connection): AdapterInterface { - $connection->execute(sprintf('USE %s', $this->getOption('database'))); + $connection->execute(sprintf('USE %s', $this->quoteTableName($this->getOption('database')))); return parent::setConnection($connection); } @@ -1242,15 +1242,15 @@ public function createDatabase(string $name, array $options = []): void if (isset($options['collation'])) { $this->execute(sprintf( - 'CREATE DATABASE `%s` DEFAULT CHARACTER SET `%s` COLLATE `%s`', - $name, + 'CREATE DATABASE %s DEFAULT CHARACTER SET `%s` COLLATE `%s`', + $this->quoteTableName($name), $charset, $options['collation'] )); } else { - $this->execute(sprintf('CREATE DATABASE `%s` DEFAULT CHARACTER SET `%s`', $name, $charset)); + $this->execute(sprintf('CREATE DATABASE %s DEFAULT CHARACTER SET `%s`', $this->quoteTableName($name), $charset)); } - $this->execute(sprintf('USE %s', $name)); + $this->execute(sprintf('USE %s', $this->quoteTableName($name))); } /** @@ -1279,7 +1279,7 @@ public function hasDatabase(string $name): bool */ public function dropDatabase(string $name): void { - $this->execute(sprintf('DROP DATABASE IF EXISTS `%s`', $name)); + $this->execute(sprintf('DROP DATABASE IF EXISTS %s', $this->quoteTableName($name))); $this->createdTables = []; } diff --git a/tests/TestCase/Db/Adapter/MysqlAdapterTest.php b/tests/TestCase/Db/Adapter/MysqlAdapterTest.php index d239f90f..c16d4a8e 100644 --- a/tests/TestCase/Db/Adapter/MysqlAdapterTest.php +++ b/tests/TestCase/Db/Adapter/MysqlAdapterTest.php @@ -104,6 +104,14 @@ public function testSchemaTableIsCreatedWithPrimaryKey() $this->assertTrue($this->adapter->hasIndex($this->adapter->getSchemaTableName(), ['version'])); } + public function testDatabaseNameWithEscapedCharacter() + { + $this->adapter->dropDatabase($this->config['database'] . '-test'); + $this->adapter->createDatabase($this->config['database'] . '-test', ['charset' => 'utf8mb4']); + $this->assertTrue($this->adapter->hasDatabase($this->config['database'] . '-test')); + $this->adapter->dropDatabase($this->config['database'] . '-test'); + } + public function testQuoteTableName() { $this->assertEquals('`test_table`', $this->adapter->quoteTableName('test_table'));