Cleanup of database reset and cleanup
This commit is contained in:
102
app/Console/Commands/CreateDatabase.php
Normal file
102
app/Console/Commands/CreateDatabase.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Symfony\Component\Process\Exception\ProcessFailedException;
|
||||
|
||||
|
||||
class CreateDatabase extends Command
|
||||
{
|
||||
protected $signature = 'database:create {--reset}';
|
||||
protected $description = 'Create a database';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function runCommand($cmd)
|
||||
{
|
||||
$cmd = join(' ', $cmd);
|
||||
|
||||
$this->info('Running "' . $cmd . '"');
|
||||
|
||||
$proc = new Process($cmd);
|
||||
$proc->run();
|
||||
if (!$proc->isSuccessful()) {
|
||||
throw new ProcessFailedException($proc);
|
||||
}
|
||||
|
||||
echo $proc->getOutput();
|
||||
}
|
||||
|
||||
protected function create_mysql($dbkey)
|
||||
{
|
||||
$mysql_cmd = [
|
||||
'mysql',
|
||||
'-u' . config($dbkey . 'username'),
|
||||
'-p' . config($dbkey . 'password'),
|
||||
'-h' . config($dbkey . 'host'),
|
||||
'-P' . config($dbkey . 'port'),
|
||||
];
|
||||
|
||||
if ($this->option('reset')) {
|
||||
$cmd = array_merge(
|
||||
$mysql_cmd,
|
||||
["-e 'DROP DATABASE ".config($dbkey . 'database')."'"]
|
||||
);
|
||||
|
||||
$this->runCommand($cmd);
|
||||
}
|
||||
|
||||
$cmd = array_merge(
|
||||
$mysql_cmd,
|
||||
["-e 'CREATE DATABASE IF NOT EXISTS " . config($dbkey . 'database') . "'"]
|
||||
);
|
||||
|
||||
$this->runCommand($cmd);
|
||||
}
|
||||
|
||||
protected function create_sqlite($dbkey)
|
||||
{
|
||||
if ($this->option('reset')) {
|
||||
$cmd = ['rm', '-rf', config($dbkey . 'database')];
|
||||
$this->runCommand($cmd);
|
||||
}
|
||||
|
||||
$cmd = [
|
||||
'sqlite3',
|
||||
config($dbkey . 'database'),
|
||||
'""',
|
||||
];
|
||||
|
||||
$this->runCommand($cmd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->info('Using connection "'.config('database.default').'"');
|
||||
|
||||
$dbkey = 'database.connections.' . config('database.default').'.';
|
||||
|
||||
if(config($dbkey.'driver') === 'mysql') {
|
||||
$this->create_mysql($dbkey);
|
||||
}
|
||||
|
||||
elseif (config($dbkey . 'driver') === 'sqlite') {
|
||||
$this->create_sqlite($dbkey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ class Kernel extends ConsoleKernel
|
||||
* @var array
|
||||
*/
|
||||
protected $commands = [
|
||||
//
|
||||
Commands\CreateDatabase::class,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user