Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions packages/database/src/QueryStatements/InsertStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,19 @@ public function compile(DatabaseDialect $dialect): string
})
->implode(', ');

$sql = sprintf(
'INSERT INTO %s (%s) VALUES %s',
$this->table,
$columns->map(fn (string $column) => "`{$column}`")->implode(', '),
$entryPlaceholders,
);
if ($columns->isEmpty()) {
$sql = match ($dialect) {
DatabaseDialect::MYSQL => sprintf('INSERT INTO %s () VALUES ()', $this->table),
default => sprintf('INSERT INTO %s DEFAULT VALUES', $this->table),
};
} else {
$sql = sprintf(
'INSERT INTO %s (%s) VALUES %s',
$this->table,
$columns->map(fn (string $column) => "`{$column}`")->implode(', '),
$entryPlaceholders,
);
}

if ($dialect === DatabaseDialect::POSTGRESQL) {
$sql .= ' RETURNING *';
Expand Down
10 changes: 10 additions & 0 deletions packages/database/tests/QueryStatements/InsertStatementTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ public function test_insert_statement(): void
$this->assertSame($expectedPostgres, $statement->compile(DatabaseDialect::POSTGRESQL));
}

public function test_insert_empty_row(): void
{
$tableDefinition = new TableDefinition('foo', 'bar');
$statement = new InsertStatement($tableDefinition);

$this->assertSame('INSERT INTO `foo` AS `bar` () VALUES ()', $statement->compile(DatabaseDialect::MYSQL));
$this->assertSame('INSERT INTO `foo` AS `bar` DEFAULT VALUES', $statement->compile(DatabaseDialect::SQLITE));
$this->assertSame('INSERT INTO `foo` AS `bar` DEFAULT VALUES RETURNING *', $statement->compile(DatabaseDialect::POSTGRESQL));
}

public function test_exception_on_column_mismatch(): void
{
$tableDefinition = new TableDefinition('foo', 'bar');
Expand Down
Loading