Created
September 14, 2018 16:26
-
-
Save 7audio/2da792eb2abb679f49fa5c6bafb48df9 to your computer and use it in GitHub Desktop.
Yii2 console command that logs into remote server (presumably production), makes SQL dump, downloads it and import to local DB
This file contains 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 | |
/** | |
* Yii2 console command that logs into remote server (presumably production), makes SQL dump, downloads it and import to local DB | |
*/ | |
namespace app\commands; | |
use yii\console\Controller; | |
use yii\helpers\Console; | |
use yii\console\ExitCode; | |
class DbImporterController extends Controller | |
{ | |
public $remoteHost = ''; | |
public $remoteOsUser = ''; | |
public $remoteSqlUser = ''; | |
public $remoteSqlPassword = ''; | |
public $remoteSqlDb = ''; | |
public $remotePath = ''; | |
public $localPath = ''; | |
public $localSqlUser = ''; | |
public $localSqlPassword = ''; | |
public $localSqlDb = ''; | |
public function actionIndex() | |
{ | |
if (Console::confirm("Import remote DB {$this->remoteSqlDb} from host {$this->remoteHost} into local {$this->localSqlDb}?")) { | |
$this->stdout("making sql dump\n", Console::FG_YELLOW); | |
$commandSqlDump = "ssh {$this->remoteOsUser}@{$this->remoteHost} \" mysqldump -p\\\"{$this->remoteSqlPassword}\\\" -u {$this->remoteSqlUser} {$this->remoteSqlDb} > {$this->remotePath}\""; | |
$this->stdout($commandSqlDump."\n"); | |
exec($commandSqlDump); | |
$this->stdout("downloading\n", Console::FG_YELLOW); | |
$commandDownload = "scp {$this->remoteOsUser}@{$this->remoteHost}:{$this->remotePath} {$this->localPath}"; | |
$this->stdout($commandDownload."\n"); | |
exec($commandDownload); | |
$this->stdout("importing\n", Console::FG_YELLOW); | |
$commandImport = "mysql -p\"{$this->localSqlPassword}\" -u {$this->localSqlUser} {$this->localSqlDb} < {$this->localPath}"; | |
$this->stdout($commandImport."\n"); | |
exec($commandImport, $output, $exitVar); | |
if ($exitVar === ExitCode::OK) { | |
$this->stdout("done\n", Console::BG_GREEN); | |
} else { | |
$this->stdout("error occured\n", Console::BG_RED); | |
} | |
} else { | |
$this->stdout("stopped\n", Console::BG_YELLOW); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment