Skip to content

Commit

Permalink
allow insert..select (insertUsing()) to have empty $columns
Browse files Browse the repository at this point in the history
Enables queries which insert *all* columns from the source table into the destination table, e.g. "insert into users select * from users”, when the table schemas exactly match.
  • Loading branch information
jonnott committed Mar 27, 2023
1 parent 4deaad7 commit cc12400
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Illuminate/Database/Query/Grammars/Grammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -1062,7 +1062,13 @@ public function compileInsertGetId(Builder $query, $values, $sequence)
*/
public function compileInsertUsing(Builder $query, array $columns, string $sql)
{
return "insert into {$this->wrapTable($query->from)} ({$this->columnize($columns)}) $sql";
$table = $this->wrapTable($query->from);

if (empty($columns)) {
return "insert into {$table} $sql";
}

return "insert into {$table} ({$this->columnize($columns)}) $sql";
}

/**
Expand Down
15 changes: 15 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2793,6 +2793,21 @@ function (Builder $query) {

$this->assertEquals(1, $result);
}

public function testInsertUsingWithEmptyColumns()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('affectingStatement')->once()->with('insert into "table1" select * from "table2" where "foreign_id" = ?', [5])->andReturn(1);

$result = $builder->from('table1')->insertUsing(
[],
function (Builder $query) {
$query->from('table2')->where('foreign_id', '=', 5);
}
);

$this->assertEquals(1, $result);
}

public function testInsertUsingInvalidSubquery()
{
Expand Down

0 comments on commit cc12400

Please sign in to comment.