Skip to content

Commit d537bd7

Browse files
Fix primary key creation for MySQL with sql_require_primary_key enabled (#7328)
1 parent 50f79d0 commit d537bd7

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

src/Schema/Blueprint.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,10 @@ public function toSql(Connection $connection, Grammar $grammar)
153153
$this->ensureCommandsAreValid($connection);
154154

155155
foreach ($this->commands as $command) {
156+
if ($command->shouldBeSkipped) {
157+
continue;
158+
}
159+
156160
$method = 'compile' . ucfirst($command->name);
157161

158162
if (method_exists($grammar, $method)) {

src/Schema/Grammars/MySqlGrammar.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -529,11 +529,23 @@ public function typeMultiPolygon(Fluent $column)
529529
*/
530530
protected function compileCreateTable($blueprint, $command, $connection)
531531
{
532+
$tableStructure = $this->getColumns($blueprint);
533+
534+
if ($primaryKey = $this->getCommandByName($blueprint, 'primary')) {
535+
$tableStructure[] = sprintf(
536+
'primary key %s(%s)',
537+
$primaryKey->algorithm ? 'using ' . $primaryKey->algorithm : '',
538+
$this->columnize($primaryKey->columns)
539+
);
540+
541+
$primaryKey->shouldBeSkipped = true;
542+
}
543+
532544
return sprintf(
533545
'%s table %s (%s)',
534546
$blueprint->temporary ? 'create temporary' : 'create',
535547
$this->wrapTable($blueprint),
536-
implode(', ', $this->getColumns($blueprint))
548+
implode(', ', $tableStructure)
537549
);
538550
}
539551

tests/MySqlSchemaGrammarTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,18 @@ public function testBasicCreateTable()
6464

6565
$this->assertCount(1, $statements);
6666
$this->assertSame('alter table `users` add `id` int unsigned not null auto_increment primary key, add `email` varchar(255) not null', $statements[0]);
67+
68+
$blueprint = new Blueprint('users');
69+
$blueprint->create();
70+
$blueprint->uuid('id')->primary();
71+
72+
$conn = $this->getConnection();
73+
$conn->shouldReceive('getConfig')->andReturn(null);
74+
75+
$statements = $blueprint->toSql($conn, $this->getGrammar());
76+
77+
$this->assertCount(1, $statements);
78+
$this->assertSame('create table `users` (`id` char(36) not null, primary key (`id`))', $statements[0]);
6779
}
6880

6981
public function testNullableMorphs()

0 commit comments

Comments
 (0)