47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
|
|
class PopulateTableFromSql extends Command
|
|
{
|
|
protected $signature = 'sql:populate {file} {--connection=}';
|
|
protected $description = 'Populate tables from a SQL file';
|
|
|
|
public function handle()
|
|
{
|
|
$file = $this->argument('file');
|
|
$path = base_path($file);
|
|
//$path = File::path($file);
|
|
|
|
if (!File::exists($path)) {
|
|
$this->error("SQL file not found: {$path}");
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$sql = File::get($path);
|
|
|
|
|
|
|
|
|
|
$connection = $this->option('connection') ?: config('database.default');
|
|
$pdo = DB::connection($connection)->getPdo();
|
|
|
|
// Naive split; works for many simple SQL files. For complex dumps,
|
|
// consider using a DB-specific import (Option B).
|
|
$statements = array_filter(array_map('trim', preg_split('/;\s*[\r\n]+/', $sql)));
|
|
|
|
foreach ($statements as $stmt) {
|
|
if ($stmt !== '') {
|
|
$pdo->exec($stmt);
|
|
}
|
|
}
|
|
|
|
$this->info('SQL import complete.');
|
|
return self::SUCCESS;
|
|
}
|
|
}
|