1 | <?php |
||
11 | class DbClear extends Command |
||
12 | { |
||
13 | use ConfirmableTrait; |
||
14 | |||
15 | /** |
||
16 | * The name and signature of the console command. |
||
17 | * |
||
18 | * @var string |
||
19 | */ |
||
20 | protected $signature = 'db:clear {--database= : The database connection to use.} |
||
21 | {--force : Force the operation to run when in production.} |
||
22 | {--pretend : Dump the SQL queries that would be run.}'; |
||
23 | |||
24 | /** |
||
25 | * The console command description. |
||
26 | * |
||
27 | * @var string |
||
28 | */ |
||
29 | protected $description = 'Clear database'; |
||
30 | |||
31 | /** |
||
32 | * Execute the console command. |
||
33 | * |
||
34 | * @return mixed |
||
35 | */ |
||
36 | public function handle(): void |
||
37 | { |
||
38 | if (! $this->confirmToProceed('Application In Production! Will be dropped all tables!')) { |
||
39 | return; |
||
40 | } |
||
41 | |||
42 | $dbConn = $this->getDatabase(); |
||
43 | $connection = DB::connection($dbConn); |
||
44 | |||
45 | $database = $connection->getDatabaseName(); |
||
46 | $tables = $connection->select('SHOW TABLES'); |
||
47 | |||
48 | if (empty($tables)) { |
||
49 | $this->info('Tables not found in database "' . $database . '"'); |
||
50 | |||
51 | return; |
||
52 | } |
||
53 | |||
54 | $pretend = $this->input->getOption('pretend'); |
||
55 | $connection->transaction(function () use ($connection, $tables, $database, $pretend) { |
||
56 | if (! $pretend) { |
||
57 | $connection->statement('SET FOREIGN_KEY_CHECKS=0;'); |
||
58 | } |
||
59 | |||
60 | foreach ($tables as $table) { |
||
61 | foreach ($table as $key => $value) { |
||
62 | $stm = 'DROP TABLE IF EXISTS `' . $value . '`'; |
||
63 | if ($pretend) { |
||
64 | $this->line("{$stm}"); |
||
65 | } else { |
||
66 | $connection->statement($stm); |
||
67 | $this->comment('Table `' . $value . '` dropped'); |
||
68 | } |
||
69 | } |
||
70 | } |
||
71 | if ($pretend) { |
||
72 | return; |
||
73 | } |
||
74 | |||
75 | $connection->statement('SET FOREIGN_KEY_CHECKS=1;'); |
||
76 | $this->info('All tables dropped from database "' . $database . '"!'); |
||
77 | }); |
||
78 | } |
||
79 | |||
80 | protected function getDatabase(): string |
||
86 | } |
||
87 |