Files
project-replica/app/Console/Commands/RunMigration.php
2026-03-23 00:51:38 +09:00

82 lines
2.1 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\MigrationSchedule;
use App\Models\MigrationRun;
use App\Jobs\RunMigrationJob;
use Illuminate\Console\Command;
class RunMigration extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migration:run {schedule? : The schedule ID to run}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run a migration schedule immediately';
/**
* Execute the console command.
*/
public function handle(): int
{
$scheduleId = $this->argument('schedule');
if ($scheduleId) {
$schedule = MigrationSchedule::find($scheduleId);
if (!$schedule) {
$this->error("Schedule with ID {$scheduleId} not found.");
return Command::FAILURE;
}
$this->runSchedule($schedule);
} else {
// Run all due schedules
$schedules = MigrationSchedule::where('is_active', true)
->where(function ($query) {
$query->whereNull('next_run_at')
->orWhere('next_run_at', '<=', now());
})
->get();
if ($schedules->isEmpty()) {
$this->info('No schedules due to run.');
return Command::SUCCESS;
}
foreach ($schedules as $schedule) {
$this->runSchedule($schedule);
}
}
return Command::SUCCESS;
}
/**
* Run a specific schedule
*/
private function runSchedule(MigrationSchedule $schedule): void
{
$this->info("Running migration schedule: {$schedule->name}");
$migrationRun = MigrationRun::create([
'schedule_id' => $schedule->id,
'status' => 'pending',
'total_tables' => count($schedule->tables),
]);
RunMigrationJob::dispatch($migrationRun);
$this->info("Migration job dispatched. Run ID: {$migrationRun->id}");
}
}