Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Fix SQLite delete for complex delete statements #22298

Merged
merged 4 commits into from
Dec 6, 2017
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
40 changes: 40 additions & 0 deletions src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Database\Query\Grammars;

use Illuminate\Support\Arr;
use Illuminate\Database\Query\Builder;

class SQLiteGrammar extends Grammar
Expand Down Expand Up @@ -174,6 +175,45 @@ public function compileInsert(Builder $query, array $values)
return "insert into $table ($names) select ".implode(' union all select ', $columns);
}

/**
* Compile a delete statement into SQL.
*
* @param \Illuminate\Database\Query\Builder $query
* @return string
*/
public function compileDelete(Builder $query)
{
// SQLite delete statement doesn't fully support complex keywords like joins ..
// We use select statement as a sub-query to overcome this dilemma.
if (isset($query->joins) || isset($query->limit)) {
// Since rowid is common column between all SQLite tables,
// we use it in select sub-query and in delete where-in statement.
$selectSql = parent::compileSelect($query->select("{$query->from}.rowid"));

return "delete from {$this->wrapTable($query->from)} where {$this->wrap('rowid')} in ({$selectSql})";
}

$wheres = is_array($query->wheres) ? $this->compileWheres($query) : '';

return trim("delete from {$this->wrapTable($query->from)} $wheres");
}

/**
* Prepare the bindings for a delete statement.
*
* @param array $bindings
* @param array $values
* @return array
*/
public function prepareBindingsForDelete(array $bindings)
{
$cleanBindings = Arr::except($bindings, ['join', 'select']);

return array_values(
array_merge($bindings['join'], Arr::flatten($cleanBindings))
);
}

/**
* Compile a truncate table statement into SQL.
*
Expand Down
11 changes: 11 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1578,6 +1578,12 @@ public function testDeleteMethod()
$result = $builder->from('users')->delete(1);
$this->assertEquals(1, $result);

$builder = $this->getSqliteBuilder();
$builder->getConnection()->shouldReceive('delete')->once()->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" where "email" = ? order by "id" asc limit 1)', ['foo'])->andReturn(1);
$result = $builder->from('users')->where('email', '=', 'foo')->orderBy('id')->take(1)->delete();
$this->assertEquals(1, $result);


$builder = $this->getMySqlBuilder();
$builder->getConnection()->shouldReceive('delete')->once()->with('delete from `users` where `email` = ? order by `id` asc limit 1', ['foo'])->andReturn(1);
$result = $builder->from('users')->where('email', '=', 'foo')->orderBy('id')->take(1)->delete();
Expand All @@ -1591,6 +1597,11 @@ public function testDeleteMethod()

public function testDeleteWithJoinMethod()
{
$builder = $this->getSqliteBuilder();
$builder->getConnection()->shouldReceive('delete')->once()->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."email" = ? order by "users"."id" asc limit 1)', ['foo'])->andReturn(1);
$result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('users.email', '=', 'foo')->orderBy('users.id')->limit(1)->delete();
$this->assertEquals(1, $result);

$builder = $this->getMySqlBuilder();
$builder->getConnection()->shouldReceive('delete')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', ['foo'])->andReturn(1);
$result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete();
Expand Down
70 changes: 70 additions & 0 deletions tests/Integration/Database/EloquentDeleteTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace Illuminate\Tests\Integration\Database;

use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Model;

/**
* @group integration
*/
class EloquentDeleteTest extends TestCase
{
protected function getEnvironmentSetUp($app)
{
$app['config']->set('app.debug', 'true');

$app['config']->set('database.default', 'testbench');

$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
}

public function setUp()
{
parent::setUp();

Schema::create('posts', function ($table) {
$table->increments('id');
$table->string('title')->nullable();
$table->timestamps();
});

Schema::create('comments', function ($table) {
$table->increments('id');
$table->string('body')->nullable();
$table->integer('post_id');
$table->timestamps();
});
}

public function testOnlyDeleteWhatGiven()
{
for($i = 1; $i <= 10; $i++) {
Comment::create([
'post_id' => Post::create()->id
]);
}

Post::latest('id')->limit(1)->delete();
$this->assertEquals(9, Post::all()->count());

Post::join('comments', 'comments.post_id', '=', 'posts.id')->where('posts.id', '>', 1)->orderBy('posts.id')->limit(1)->delete();
$this->assertEquals(8, Post::all()->count());
}
}

class Post extends Model
{
public $table = 'posts';
}

class Comment extends Model
{
public $table = 'comments';
protected $fillable = ['post_id'];
}