Files
dyncoll-dev/backend/app/Console/Commands/V1ImportCommand.php
2026-06-22 22:14:15 +02:00

92 lines
2.7 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Etl\Contracts\Importer;
use App\Etl\Importers\InstitutionImporter;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* ETL idempotente dal DB legacy (v1) allo schema v2.
*
* Orchestra gli importer in ORDINE DI DIPENDENZA (institutions prima delle entità
* che le referenziano, es. artifacts). Ogni importer legge dalla connessione
* `legacy` e scrive su quella di default. Serve sia per i refresh di sviluppo
* sia per la migrazione di cutover.
*/
class V1ImportCommand extends Command
{
protected $signature = 'v1:import
{--only=* : Limit to specific importers (e.g. --only=institutions)}
{--dry-run : Read and count without writing}';
protected $description = 'Import data from the legacy (v1) database into the v2 schema (idempotent)';
/**
* Importer in ordine di dipendenza.
*
* @var list<class-string<Importer>>
*/
private array $importers = [
InstitutionImporter::class,
];
public function handle(): int
{
$dryRun = (bool) $this->option('dry-run');
$only = array_map('strtolower', (array) $this->option('only'));
try {
DB::connection('legacy')->getPdo();
} catch (Throwable $e) {
$this->error('Legacy connection unavailable: '.$e->getMessage());
$this->line('Set DB_LEGACY_* in the environment (see config/database.php → connections.legacy).');
return self::FAILURE;
}
if ($dryRun) {
$this->warn('DRY-RUN: no data will be written.');
}
$hadError = false;
foreach ($this->importers as $class) {
/** @var Importer $importer */
$importer = app($class);
if ($only !== [] && ! in_array($importer->key(), $only, true)) {
continue;
}
$this->info("{$importer->label()}");
try {
$summary = $importer->import($dryRun);
} catch (Throwable $e) {
$this->error(" {$importer->key()} failed: ".$e->getMessage());
$hadError = true;
continue;
}
foreach ($summary->warnings as $warning) {
$this->warn(' ! '.$warning);
}
$this->line(sprintf(
' %screated %d, updated %d, skipped %d (total %d)',
$dryRun ? '[dry-run] ' : '',
$summary->created,
$summary->updated,
$summary->skipped,
$summary->total(),
));
}
return $hadError ? self::FAILURE : self::SUCCESS;
}
}