Skip to content

Commit

Permalink
[10.x] Fix primary key creation for MySQL with `sql_require_primary_k…
Browse files Browse the repository at this point in the history
…ey` enabled (#49374)

* Fix inline primary key creation for MySQL

* Fix styleci issue

* Correct comment sentence

* Refactor

* Add tests

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
mtawil and taylorotwell committed Dec 14, 2023
1 parent c80d3eb commit 59f184e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/Illuminate/Database/Schema/Blueprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ public function toSql(Connection $connection, Grammar $grammar)
$this->ensureCommandsAreValid($connection);

foreach ($this->commands as $command) {
if ($command->shouldBeSkipped) {
continue;
}

$method = 'compile'.ucfirst($command->name);

if (method_exists($grammar, $method) || $grammar::hasMacro($method)) {
Expand Down
14 changes: 13 additions & 1 deletion src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,22 @@ public function compileCreate(Blueprint $blueprint, Fluent $command, Connection
*/
protected function compileCreateTable($blueprint, $command, $connection)
{
$tableStructure = $this->getColumns($blueprint);

if ($primaryKey = $this->getCommandByName($blueprint, 'primary')) {
$tableStructure[] = sprintf(
'primary key %s(%s)',
$primaryKey->algorithm ? 'using '.$primaryKey->algorithm : '',
$this->columnize($primaryKey->columns)
);

$primaryKey->shouldBeSkipped = true;
}

return sprintf('%s table %s (%s)',
$blueprint->temporary ? 'create temporary' : 'create',
$this->wrapTable($blueprint),
implode(', ', $this->getColumns($blueprint))
implode(', ', $tableStructure)
);
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseMySqlSchemaGrammarTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ public function testBasicCreateTable()

$this->assertCount(1, $statements);
$this->assertSame('alter table `users` add `id` int unsigned not null auto_increment primary key, add `email` varchar(255) not null', $statements[0]);

$blueprint = new Blueprint('users');
$blueprint->create();
$blueprint->uuid('id')->primary();

$conn = $this->getConnection();
$conn->shouldReceive('getConfig')->andReturn(null);

$statements = $blueprint->toSql($conn, $this->getGrammar());

$this->assertCount(1, $statements);
$this->assertSame('create table `users` (`id` char(36) not null, primary key (`id`))', $statements[0]);
}

public function testAutoIncrementStartingValue()
Expand Down

0 comments on commit 59f184e

Please sign in to comment.