Last active
March 4, 2018 12:45
-
-
Save shmurakami/c73a7542449ed3543c1be55f778175e5 to your computer and use it in GitHub Desktop.
Generate sqlite database for Laravel/Lumen Console command
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 | |
use DB; | |
use Illuminate\Console\Command; | |
class RefreshUnitTestDB extends Command | |
{ | |
protected $signature = 'test:refresh-unit-test-db'; | |
protected $description = 'Refresh local sqlitedb for API test'; | |
public function handle() | |
{ | |
$converterCommandPath = storage_path('app/mysql2sqlite/mysql2sqlite'); | |
if (!file_exists($converterCommandPath)) { | |
$this->error('First you have to clone this repository to storage/app'); | |
$this->error('https://github.com/dumblob/mysql2sqlite'); | |
return 1; | |
} | |
exec('which sqlite3', $output, $status); | |
if ($status !== 0) { | |
$this->error('This command requires to install sqlite3 command on your machine'); | |
$this->error('Install sqlite3 by brew or something'); | |
return 1; | |
} | |
// make dump only table structure to storage | |
$dumpFilePath = storage_path('app/db_tables.sql'); | |
$dumpCommand = sprintf("mysqldump -u %s -p%s -d %s > $dumpFilePath 2> /dev/null", | |
config('database.connections.mysql.username'), | |
config('database.connections.mysql.password'), | |
config('database.connections.mysql.database') | |
); | |
exec($dumpCommand, $output, $status); | |
if ($status !== 0) { | |
$this->error('failed to dump mysql'); | |
return 1; | |
} | |
// make sqlite with latest database dump | |
$sqlitePath = storage_path('local.db'); | |
unlink($sqlitePath); | |
$generateSqliteCommand = "$converterCommandPath $dumpFilePath |sqlite3 $sqlitePath"; | |
exec($generateSqliteCommand, $output, $status); | |
if ($status !== 0) { | |
$this->error('failed to generate new sqlite file'); | |
return 1; | |
} | |
unlink($dumpFilePath); | |
$this->info('Succeeded'); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment