Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save minedun6/5cdaf58a6647718c3c6904d50e1d6187 to your computer and use it in GitHub Desktop.
Save minedun6/5cdaf58a6647718c3c6904d50e1d6187 to your computer and use it in GitHub Desktop.
Import Remote DB with Laravel.
<?php
//import db from original server to local one...
/**
* Instructions:
* 1. Install this package: https://laravelcollective.com/docs/5.3/ssh
* 2. Add those to your .env file and fill up the values:
ORIGINAL_SERVER_SSH_ADDRESS=
ORIGINAL_SERVER_SSH_USERNAME=
ORIGINAL_SERVER_SSH_PASSWORD=
ORIGINAL_SERVER_MYSQL_USERNAME=
ORIGINAL_SERVER_MYSQL_PASSWORD=
ORIGINAL_SERVER_MYSQL_DATABASE=
LOCAL_SERVER_MYSQL_DATABASE=
LOCAL_SERVER_MYSQL_USERNAME=
LOCAL_SERVER_MYSQL_PASSWORD=
ORIGINAL_SERVER_DB_DUMP_ARCHIVE_NAME=
ORIGINAL_SERVER_DB_DUMP_ARCHIVE_DIR=/home/
*
* 3. In your config/remote.php
* change 'default' => 'production'
* to 'default' => 'original_server'
* and in 'connections' add settings
* for your server. Example:
* https://gist.github.com/YavorK/280f9af3cd4e4163add855d3346507ea
*
* 4. use php artisan db:port-original to run the command
*
*/
Artisan::command('db:port-original', function () {
//Laravel Remote is AWESOEM // https://laravelcollective.com/docs/5.3/ssh#sftp-downloads ...
//make sure process does not get killed
set_time_limit(0);
//define some values
$archiveName = env('ORIGINAL_SERVER_DB_DUMP_ARCHIVE_NAME');
$archiveFilePath = base_path('storage' . DIRECTORY_SEPARATOR . $archiveName);
$dumpFilePath = base_path('storage' . DIRECTORY_SEPARATOR . 'do.dump');
$remoteArchivePath = env('ORIGINAL_SERVER_DB_DUMP_ARCHIVE_DIR') . $archiveName;
//dump and archive the db
$this->info("Dumping and archiving remote DB...");
SSH::into('original_server')->run([
'mysqldump -u ' . env('ORIGINAL_SERVER_MYSQL_USERNAME')
. ' -p' . env('ORIGINAL_SERVER_MYSQL_PASSWORD') . ' '
. env('ORIGINAL_SERVER_MYSQL_DATABASE')
. ' | gzip -c | cat > ' . $remoteArchivePath
]);
//download db to local
$this->info('Downloading dump file archive...');
SSH::into('original_server')->get($remoteArchivePath, $archiveFilePath);
//unzip
$this->info('Unzipping the archive...');
exec('gunzip < ' . $archiveFilePath . ' > ' . $dumpFilePath);
//add which db to use
$this->info('Adding USE statement to dump...');
exec('sed -i \'1 i\ USE `'.env('LOCAL_SERVER_MYSQL_DATABASE').'`;\' ' . $dumpFilePath);
//import it
$this->info('Importing to the local DB...');
exec('mysql -u '.env('LOCAL_SERVER_MYSQL_USERNAME').' -p'.env('LOCAL_SERVER_MYSQL_PASSWORD').' < ' . $dumpFilePath);
//delete remote dump files
$this->info("Remove remote archive... ");
SSH::into('original_server')->run([
'rm -f ' . $remoteArchivePath
]);
//delete local dump files
$this->info("Remove local files... ");
@unlink($dumpFilePath);
@unlink($archiveFilePath);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment