Skip to content

Commit

Permalink
allow insert..select (insertUsing()) to have empty $columns (#46605)
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.

alter testPreservedAreAppliedByInsertUsing() to not conflict with new behaviour
  • Loading branch information
jonnott authored Mar 28, 2023
1 parent c2dc395 commit a84264d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
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
19 changes: 17 additions & 2 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2794,6 +2794,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()
{
$this->expectException(InvalidArgumentException::class);
Expand Down Expand Up @@ -3351,11 +3366,11 @@ public function testPreservedAreAppliedByInsertGetId()
public function testPreservedAreAppliedByInsertUsing()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('affectingStatement')->once()->with('insert into "users" () select *', []);
$builder->getConnection()->shouldReceive('affectingStatement')->once()->with('insert into "users" ("email") select *', []);
$builder->beforeQuery(function ($builder) {
$builder->from('users');
});
$builder->insertUsing([], $this->getBuilder());
$builder->insertUsing(['email'], $this->getBuilder());
}

public function testPreservedAreAppliedByUpsert()
Expand Down

0 comments on commit a84264d

Please sign in to comment.