Skip to content

Commit

Permalink
Merge pull request #717 from jharder/4.x
Browse files Browse the repository at this point in the history
Handle database with escapable identifiers in name
  • Loading branch information
markstory committed May 9, 2024
2 parents 8c4d3e1 + 9521d4b commit 830e480
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/Db/Adapter/MysqlAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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)));
}

/**
Expand Down Expand Up @@ -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 = [];
}

Expand Down
8 changes: 8 additions & 0 deletions tests/TestCase/Db/Adapter/MysqlAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down

0 comments on commit 830e480

Please sign in to comment.