greglamb
2/11/2014 - 9:18 PM

Laravel DbTabledumpCommand

Laravel DbTabledumpCommand

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

use Symfony\Component\Process\Process;

class DbTabledumpCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'db:tabledump';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'save table data';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
	    $config = Config::get('database.connections.'.Config::get('database.default'));
	    
	    if ($this->argument('table')) {
	        $tables = array($this->argument('table'));
	    } else {
	        $tables = DB::table('information_schema.tables')
	            ->where('table_catalog', $config['database'])
	            ->where('table_type', 'BASE TABLE')
	            ->whereNotIn('table_schema', array('pg_catalog','public','information_schema'))
	            ->select(DB::raw("CONCAT(table_schema,'.',table_name) as table"))->lists('table');
	    }
	    
	    foreach($tables as $table) {
            $command = sprintf('PGPASSWORD=%s pg_dump --no-acl --data-only --verbose -t %s --no-owner -h %s -U %s %s > %s',
                escapeshellarg($config['password']),
                escapeshellarg($table),
                escapeshellarg($config['host']),
                escapeshellarg($config['username']),
                escapeshellarg($config['database']),
                escapeshellarg(app_path().'/database/backup/pgtable_'.$table.'_'.date("YmdHis").'.'.uniqid().'.sql')
            );
            $process = new Process($command);
            $process->run();
            echo "Executed command : ".$command."\n";
            if ($process->isSuccessful()) {
                #return true;
            } else {
                return $process->getErrorOutput();
            }
        }
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(
		    array('table', InputArgument::OPTIONAL, 'table to export')
		);
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array();
	}

}