Skip to content

Commit 7b41fcf

Browse files
committed
db:truncate with tables argument and foreigen key checks option
1 parent e2b8210 commit 7b41fcf

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/Commands/DBTruncateCommand.php

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,27 +11,46 @@ class DBTruncateCommand extends Command
1111
{
1212
use ConfirmableTrait;
1313

14-
public $signature = 'db:truncate';
14+
protected $signature = 'db:truncate {tables?* : Optionally specify only specific tables to truncate}
15+
{--force : Force the operation to run when in production}
16+
{--checks=true : Enable or disable foreign key checks during truncation}';
1517

16-
public $description = 'Truncate all tables';
18+
protected $description = 'Truncate all tables';
1719

1820
public function handle(): int
1921
{
2022
if (! $this->confirmToProceed()) {
2123
return 1;
2224
}
2325

24-
$this->components->info('Preparing database.');
26+
$foreignKeyChecks = $this->hasOption('checks') && filter_var($this->option('checks'), FILTER_VALIDATE_BOOLEAN);
2527

26-
collect(Schema::getAllTables())->each(function ($tableDefinition) {
27-
$table = current($tableDefinition);
28+
if (!$foreignKeyChecks) {
29+
$this->components->warn('Disabling foreign key checks!');
30+
Schema::disableForeignKeyConstraints();
31+
}
32+
33+
$this->components->info('Start truncating tables.');
34+
35+
$tables = $this->argument('tables') ?: collect(Schema::getAllTables())->map(function ($tableDefinition) {
36+
return current($tableDefinition);
37+
});
38+
39+
collect($tables)->each(function ($table) {
2840
$this->components->task("Truncating table: $table", function () use ($table) {
2941
DB::table($table)->truncate();
3042
});
3143
});
3244

3345
$this->newLine();
3446

47+
$this->components->info('Finished truncating tables.');
48+
49+
if (!$foreignKeyChecks) {
50+
$this->components->warn('Re-enabling foreign key checks!');
51+
Schema::enableForeignKeyConstraints();
52+
}
53+
3554
return self::SUCCESS;
3655
}
3756
}

src/LaravelUsefulAdditionsServiceProvider.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ public function configurePackage(Package $package): void
1818
$package
1919
->name('laravel-useful-additions')
2020
->hasConfigFile()
21-
->hasCommand(DBTruncateCommand::class);;
21+
->hasCommand(DBTruncateCommand::class);
2222
}
2323
}

0 commit comments

Comments
 (0)