Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Mail;
- use Illuminate\Support\Facades\Storage;
- class DailyBackupAndSyncCommand extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'tonic:db-backup';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'Data backup for Tonic Navigator';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- $filename = "backup-" . Carbon::now()->format('Y-m-d_H-i-s') . ".sql";
- $filePath = storage_path() . "/backup/" . $filename;
- $devDatabase = "db1";
- $this->destroyCreateAndDump($filePath, $devDatabase);
- $this->info('ALL IS GOOD');
- }
- private function destroyCreateAndDump($filePath, $database)
- {
- /**
- * If the DB is remote this will be useful
- * "pg_dump --username=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " --dbname=" . env('DB_DATABASE') . "
- */
- $command = "pg_dump " . env('DB_DATABASE') . " > " . $filePath;
- exec($command);
- $this->info('DATA DUMP FROM ' . env('DB_DATABASE') . ' IS PROCESSED AND SAVED TO `'. $filePath . '`');
- DB::connection()->statement("select pg_terminate_backend(pg_stat_activity.pid) from pg_stat_activity where datname='".$database."' AND state='idle';");
- DB::connection()->statement('DROP DATABASE '.$database);
- DB::connection()->statement('CREATE DATABASE '.$database);
- $dumpDev = "psql ".$database." < " . $filePath;
- exec($dumpDev);
- $this->info('DATABASE RESTORED `'.$database.'` FROM `'. $filePath . '`');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement