Created
January 5, 2017 14:48
-
-
Save yoosuf/d8ff0b90f019333dbb260d2323ae7925 to your computer and use it in GitHub Desktop.
Daily backup and Restore Laravel Command
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
<?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 . '`'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment