-
Notifications
You must be signed in to change notification settings - Fork 11.4k
[8.x] Adds the possibility of having "Prunable" models #37889
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
452b029
Adds possibility of having "Prunable" models
nunomaduro cc42190
Apply fixes from StyleCI (#37887)
nunomaduro ddcdd8a
Addresses a few typos
nunomaduro b28b73e
Merge branch 'feat/prunable-models' of https://github.com/laravel/fra…
nunomaduro 63ba15c
Avoids hit SQLITE_MAX_VARIABLE_NUMBER in tests
nunomaduro c3af0dc
Avoids hit SQLITE_MAX_VARIABLE_NUMBER in tests
nunomaduro ee3e144
Fixes windows tests regarding the output of commands
nunomaduro c7bc710
formatting
taylorotwell 1dd702b
add configurable chunk size to prunable
taylorotwell ebadc43
add before prune hook to avoid need to call parent
taylorotwell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
<?php | ||
|
||
namespace Illuminate\Database\Console; | ||
|
||
use Illuminate\Console\Command; | ||
use Illuminate\Contracts\Events\Dispatcher; | ||
use Illuminate\Database\Eloquent\MassPrunable; | ||
use Illuminate\Database\Eloquent\Prunable; | ||
use Illuminate\Database\Events\ModelsPruned; | ||
use Illuminate\Support\Str; | ||
use Symfony\Component\Finder\Finder; | ||
|
||
class PruneCommand extends Command | ||
{ | ||
/** | ||
* The console command name. | ||
* | ||
* @var string | ||
*/ | ||
protected $signature = 'model:prune | ||
{--model=* : Class names of the models to be pruned} | ||
{--chunk=1000 : The number of models to retrieve per chunk of models to be deleted}'; | ||
|
||
/** | ||
* The console command description. | ||
* | ||
* @var string | ||
*/ | ||
protected $description = 'Prune models that are no longer needed'; | ||
|
||
/** | ||
* Execute the console command. | ||
* | ||
* @param \Illuminate\Contracts\Events\Dispatcher $events | ||
* @return void | ||
*/ | ||
public function handle(Dispatcher $events) | ||
{ | ||
$events->listen(ModelsPruned::class, function ($event) { | ||
$this->info("{$event->count} [{$event->model}] records have been pruned."); | ||
}); | ||
|
||
$this->models()->each(function ($model) { | ||
$instance = new $model; | ||
|
||
$chunkSize = property_exists($instance, 'prunableChunkSize') | ||
? $instance->prunableChunkSize | ||
: $this->option('chunk'); | ||
|
||
$total = $this->isPrunable($model) | ||
? $instance->pruneAll($chunkSize) | ||
: 0; | ||
|
||
if ($total == 0) { | ||
$this->info("No prunable [$model] records found."); | ||
} | ||
}); | ||
|
||
$events->forget(ModelsPruned::class); | ||
} | ||
|
||
/** | ||
* Determine the models that should be pruned. | ||
* | ||
* @return array | ||
*/ | ||
protected function models() | ||
{ | ||
if (! empty($models = $this->option('model'))) { | ||
return collect($models); | ||
} | ||
|
||
return collect((new Finder)->in(app_path('Models'))->files()) | ||
->map(function ($model) { | ||
$namespace = $this->laravel->getNamespace(); | ||
|
||
return $namespace.str_replace( | ||
['/', '.php'], | ||
['\\', ''], | ||
Str::after($model->getRealPath(), realpath(app_path()).DIRECTORY_SEPARATOR) | ||
); | ||
})->filter(function ($model) { | ||
return $this->isPrunable($model); | ||
})->values(); | ||
nunomaduro marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
/** | ||
* Determine if the given model class is prunable. | ||
* | ||
* @param string $model | ||
* @return bool | ||
*/ | ||
protected function isPrunable($model) | ||
{ | ||
$uses = class_uses_recursive($model); | ||
|
||
return in_array(Prunable::class, $uses) || in_array(MassPrunable::class, $uses); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
<?php | ||
|
||
namespace Illuminate\Database\Eloquent; | ||
|
||
use Illuminate\Database\Events\ModelsPruned; | ||
use LogicException; | ||
|
||
trait MassPrunable | ||
{ | ||
/** | ||
* Prune all prunable models in the database. | ||
* | ||
* @param int $chunkSize | ||
* @return int | ||
*/ | ||
public function pruneAll(int $chunkSize = 1000) | ||
{ | ||
$query = tap($this->prunable(), function ($query) use ($chunkSize) { | ||
$query->when(! $query->getQuery()->limit, function ($query) use ($chunkSize) { | ||
$query->limit($chunkSize); | ||
}); | ||
}); | ||
|
||
$total = 0; | ||
|
||
do { | ||
$total += $count = in_array(SoftDeletes::class, class_uses_recursive(get_class($this))) | ||
? $query->forceDelete() | ||
: $query->delete(); | ||
|
||
if ($count > 0) { | ||
event(new ModelsPruned(static::class, $total)); | ||
} | ||
} while ($count > 0); | ||
|
||
return $total; | ||
} | ||
|
||
/** | ||
* Get the prunable model query. | ||
* | ||
* @return \Illuminate\Database\Eloquent\Builder | ||
*/ | ||
public function prunable() | ||
{ | ||
throw new LogicException('Please implement the prunable method on your model.'); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
<?php | ||
|
||
namespace Illuminate\Database\Eloquent; | ||
|
||
use Illuminate\Database\Events\ModelsPruned; | ||
use LogicException; | ||
|
||
trait Prunable | ||
{ | ||
/** | ||
* Prune all prunable models in the database. | ||
* | ||
* @param int $chunkSize | ||
* @return int | ||
*/ | ||
public function pruneAll(int $chunkSize = 1000) | ||
{ | ||
$total = 0; | ||
|
||
$this->prunable() | ||
->when(in_array(SoftDeletes::class, class_uses_recursive(get_class($this))), function ($query) { | ||
$query->withTrashed(); | ||
})->chunkById($chunkSize, function ($models) use (&$total) { | ||
$models->each->prune(); | ||
|
||
$total += $models->count(); | ||
|
||
event(new ModelsPruned(static::class, $total)); | ||
}); | ||
|
||
return $total; | ||
} | ||
|
||
/** | ||
* Get the prunable model query. | ||
* | ||
* @return \Illuminate\Database\Eloquent\Builder | ||
*/ | ||
public function prunable() | ||
nunomaduro marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
throw new LogicException('Please implement the prunable method on your model.'); | ||
} | ||
|
||
/** | ||
* Prune the model in the database. | ||
* | ||
* @return bool|null | ||
*/ | ||
public function prune() | ||
{ | ||
$this->pruning(); | ||
|
||
return in_array(SoftDeletes::class, class_uses_recursive(get_class($this))) | ||
? $this->forceDelete() | ||
: $this->delete(); | ||
} | ||
|
||
/** | ||
* Prepare the model for pruning. | ||
* | ||
* @return void | ||
*/ | ||
protected function pruning() | ||
{ | ||
// | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
<?php | ||
|
||
namespace Illuminate\Database\Events; | ||
|
||
class ModelsPruned | ||
{ | ||
/** | ||
* The class name of the model that was pruned. | ||
* | ||
* @var string | ||
*/ | ||
public $model; | ||
|
||
/** | ||
* The number of pruned records. | ||
* | ||
* @var int | ||
*/ | ||
public $count; | ||
|
||
/** | ||
* Create a new event instance. | ||
* | ||
* @param string $model | ||
* @param int $count | ||
* @return void | ||
*/ | ||
public function __construct($model, $count) | ||
{ | ||
$this->model = $model; | ||
$this->count = $count; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
<?php | ||
|
||
namespace Illuminate\Tests\Database; | ||
|
||
use Illuminate\Container\Container; | ||
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; | ||
use Illuminate\Database\Console\PruneCommand; | ||
use Illuminate\Database\Eloquent\MassPrunable; | ||
use Illuminate\Database\Eloquent\Model; | ||
use Illuminate\Database\Eloquent\Prunable; | ||
use Illuminate\Database\Events\ModelsPruned; | ||
use Illuminate\Events\Dispatcher; | ||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Component\Console\Input\ArrayInput; | ||
use Symfony\Component\Console\Output\BufferedOutput; | ||
|
||
class PruneCommandTest extends TestCase | ||
{ | ||
protected function setUp(): void | ||
{ | ||
parent::setUp(); | ||
|
||
Container::setInstance($container = new Container); | ||
|
||
$container->singleton(DispatcherContract::class, function () { | ||
return new Dispatcher(); | ||
}); | ||
|
||
$container->alias(DispatcherContract::class, 'events'); | ||
} | ||
|
||
public function testPrunableModelWithPrunableRecords() | ||
{ | ||
$output = $this->artisan(['--model' => PrunableTestModelWithPrunableRecords::class]); | ||
|
||
$this->assertEquals(<<<'EOF' | ||
10 [Illuminate\Tests\Database\PrunableTestModelWithPrunableRecords] records have been pruned. | ||
20 [Illuminate\Tests\Database\PrunableTestModelWithPrunableRecords] records have been pruned. | ||
|
||
EOF, str_replace("\r", '', $output->fetch())); | ||
} | ||
|
||
public function testPrunableTestModelWithoutPrunableRecords() | ||
{ | ||
$output = $this->artisan(['--model' => PrunableTestModelWithoutPrunableRecords::class]); | ||
|
||
$this->assertEquals(<<<'EOF' | ||
No prunable [Illuminate\Tests\Database\PrunableTestModelWithoutPrunableRecords] records found. | ||
|
||
EOF, str_replace("\r", '', $output->fetch())); | ||
} | ||
|
||
public function testNonPrunableTest() | ||
{ | ||
$output = $this->artisan(['--model' => NonPrunableTestModel::class]); | ||
|
||
$this->assertEquals(<<<'EOF' | ||
No prunable [Illuminate\Tests\Database\NonPrunableTestModel] records found. | ||
|
||
EOF, str_replace("\r", '', $output->fetch())); | ||
} | ||
|
||
protected function artisan($arguments) | ||
{ | ||
$input = new ArrayInput($arguments); | ||
$output = new BufferedOutput; | ||
|
||
tap(new PruneCommand()) | ||
->setLaravel(Container::getInstance()) | ||
->run($input, $output); | ||
|
||
return $output; | ||
} | ||
|
||
public function tearDown(): void | ||
{ | ||
parent::tearDown(); | ||
|
||
Container::setInstance(null); | ||
} | ||
} | ||
|
||
class PrunableTestModelWithPrunableRecords extends Model | ||
{ | ||
use MassPrunable; | ||
|
||
public function pruneAll() | ||
{ | ||
event(new ModelsPruned(static::class, 10)); | ||
event(new ModelsPruned(static::class, 20)); | ||
|
||
return 20; | ||
} | ||
} | ||
|
||
class PrunableTestModelWithoutPrunableRecords extends Model | ||
{ | ||
use Prunable; | ||
|
||
public function pruneAll() | ||
{ | ||
return 0; | ||
} | ||
} | ||
|
||
class NonPrunableTestModel extends Model | ||
{ | ||
// .. | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.