-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportDatabaseCommand.php
More file actions
80 lines (71 loc) · 2.2 KB
/
Copy pathImportDatabaseCommand.php
File metadata and controls
80 lines (71 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace App\Console\Commands;
use phpseclib3\Net\SFTP;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class ImportDatabaseCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'database:import {file}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import a SQL file into the database';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->truncate();
$this->dump();
$this->populate();
}
private function truncate():void
{
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();
foreach ($tables as $table) {
DB::table($table)->truncate();
$this->info("Table $table truncated successfully.");
}
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
private function dump():void
{
$sftp = new SFTP(env('SSH_DOMAIN'));
if (! $sftp->login(env('SSH_USER'), env('SSH_PASSWORD'))) {
$this->error('Falha no Login!');
return;
}
$dumpFile = $this->argument('file');
$sftp->exec('cd '.env('SSH_PROJECT_PATH'));
$sftp->exec("mysqldump -u ".env('SSH_DB_USER')." -p'".env('SSH_DB_PASSWORD')."' ".env('SSH_DB_NAME')." > $dumpFile --no-create-info ");
$contents = $sftp->get($dumpFile);
if (!is_string($contents)) {
$this->error('Falha no Dump!');
return;
}
Storage::disk('public')->put($dumpFile, $contents);
$sftp->delete($dumpFile);
$this->info('Dump realizado com sucesso!');
}
private function populate():void
{
$file = $this->argument('file');
if (! Storage::disk('public')->exists($file)) {
$this->error('Falha na hora de importar os dados!');
return;
}
DB::unprepared(Storage::disk('public')->get($file));
$this->info('Importação concluída com sucesso!');
}
}