Skip to content

Commit 5c2a500

Browse files
authored
fix(database): support inserting empty rows (#1515)
1 parent b33204f commit 5c2a500

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

packages/database/src/QueryStatements/InsertStatement.php

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,19 @@ public function compile(DatabaseDialect $dialect): string
4646
})
4747
->implode(', ');
4848

49-
$sql = sprintf(
50-
'INSERT INTO %s (%s) VALUES %s',
51-
$this->table,
52-
$columns->map(fn (string $column) => "`{$column}`")->implode(', '),
53-
$entryPlaceholders,
54-
);
49+
if ($columns->isEmpty()) {
50+
$sql = match ($dialect) {
51+
DatabaseDialect::MYSQL => sprintf('INSERT INTO %s () VALUES ()', $this->table),
52+
default => sprintf('INSERT INTO %s DEFAULT VALUES', $this->table),
53+
};
54+
} else {
55+
$sql = sprintf(
56+
'INSERT INTO %s (%s) VALUES %s',
57+
$this->table,
58+
$columns->map(fn (string $column) => "`{$column}`")->implode(', '),
59+
$entryPlaceholders,
60+
);
61+
}
5562

5663
if ($dialect === DatabaseDialect::POSTGRESQL) {
5764
$sql .= ' RETURNING *';

packages/database/tests/QueryStatements/InsertStatementTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ public function test_insert_statement(): void
3131
$this->assertSame($expectedPostgres, $statement->compile(DatabaseDialect::POSTGRESQL));
3232
}
3333

34+
public function test_insert_empty_row(): void
35+
{
36+
$tableDefinition = new TableDefinition('foo', 'bar');
37+
$statement = new InsertStatement($tableDefinition);
38+
39+
$this->assertSame('INSERT INTO `foo` AS `bar` () VALUES ()', $statement->compile(DatabaseDialect::MYSQL));
40+
$this->assertSame('INSERT INTO `foo` AS `bar` DEFAULT VALUES', $statement->compile(DatabaseDialect::SQLITE));
41+
$this->assertSame('INSERT INTO `foo` AS `bar` DEFAULT VALUES RETURNING *', $statement->compile(DatabaseDialect::POSTGRESQL));
42+
}
43+
3444
public function test_exception_on_column_mismatch(): void
3545
{
3646
$tableDefinition = new TableDefinition('foo', 'bar');

0 commit comments

Comments
 (0)