make(Kernel::class)->bootstrap(); $database = $argv[1] ?? ''; if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || DB::connection()->getConfig('host') !== '127.0.0.1') { throw new LogicException('Ensaio de actualização permitido apenas em PostgreSQL sintético isolado.'); } $targets = ['2026_11_21_000001_create_quotation_exchange_rates.php', '2026_11_21_000002_add_supplier_bank_account_keys.php']; $baseline = array_values(array_filter(glob(database_path('migrations/*.php')), fn ($path) => ! in_array(basename($path), $targets, true))); if (Artisan::call('migrate', ['--path' => $baseline, '--realpath' => true, '--force' => true]) !== 0) { throw new RuntimeException('Preparação do schema anterior falhou.'); } require __DIR__.'/../Support/ReceiptFixture.php'; $f = receiptFixture(); auth()->guard()->setUser($f['issuer']); $detail = app(SupplierBankWorkflow::class)->propose($f['issuer'], Supplier::query()->findOrFail($f['order']->supplier_id), ['previous_id' => 0, 'bank_name' => 'Banco sintético de transição', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Beneficiário sintético', 'account_identifier' => 'QA-LEGACY-ONLY', 'evidence_reference' => 'Evidência exclusivamente sintética', 'reason' => 'Ensaio da preservação do histórico anterior.']); $tables = array_column(DB::select("select tablename from pg_tables where schemaname='public' and tablename <> 'migrations' order by tablename"), 'tablename'); $columns = []; foreach ($tables as $table) { $columns[$table] = Schema::getColumnListing($table); } $fingerprint = static function ($connection) use ($columns): array { $hashes = []; foreach ($columns as $table => $names) { $quoted = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names)); $rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.$table.'") t order by row_to_json(t)::text'); $hashes[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR)); } return $hashes; }; $before = $fingerprint(DB::connection()); $migrationCount = DB::table('migrations')->count(); $config = DB::connection()->getConfig(); unset($config['name']); $directory = storage_path('framework/testing/commercial-upgrade-'.$database); if (! mkdir($directory, 0700, true) && ! is_dir($directory)) { throw new RuntimeException('Não foi possível preparar a salvaguarda sintética.'); } $pg = static function (string $binary, array $args) use ($config): void { $process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $config['host'], 'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password']], timeout: 90); $process->run(); if (! $process->isSuccessful()) { throw new RuntimeException('Salvaguarda/restauro sintéticos não aprovados.'); } }; $preDump = $directory.'/before.dump'; $pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]); $paths = array_map(fn ($name) => database_path('migrations/'.$name), $targets); if (Artisan::call('migrate', ['--path' => $paths, '--realpath' => true, '--force' => true]) !== 0 || $fingerprint(DB::connection()) !== $before || DB::table('migrations')->count() !== $migrationCount + 2 || DB::table('quotation_exchange_rates')->exists() || DB::table('quotations')->whereNotNull('exchange_basis')->exists() || DB::table('supplier_bank_details')->whereNotNull('account_key')->exists() || SupplierBankDetail::query()->findOrFail($detail->id)->account_key !== null) { throw new RuntimeException('Actualização não preservou o schema/dados anteriores ou criou valores novos.'); } if (Artisan::call('migrate', ['--path' => $paths, '--realpath' => true, '--force' => true]) !== 0 || DB::table('migrations')->count() !== $migrationCount + 2 || $fingerprint(DB::connection()) !== $before) { throw new RuntimeException('Reexecução da migração não é inócua.'); } $restore = 'compras_receipts_test_'.bin2hex(random_bytes(6)); config(['database.connections.upgrade_admin' => [...$config, 'database' => 'postgres', 'url' => null]]); $admin = DB::connection('upgrade_admin'); $dump = $directory.'/after.dump'; $created = false; try { $pg('pg_dump', ['--format=custom', '--file='.$dump, '--dbname='.$database]); $admin->statement('CREATE DATABASE "'.$restore.'"'); $created = true; $pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump]); config(['database.connections.upgrade_restore' => [...$config, 'database' => $restore, 'url' => null]]); $restored = DB::connection('upgrade_restore'); if ($fingerprint($restored) !== $before || $restored->table('migrations')->count() !== $migrationCount + 2 || $restored->table('quotation_exchange_rates')->exists() || $restored->table('supplier_bank_details')->whereNotNull('account_key')->exists()) { throw new RuntimeException('Restauro não conserva a actualização e os dados anteriores.'); } DB::purge('upgrade_restore'); $admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)'); $created = false; $admin->statement('CREATE DATABASE "'.$restore.'"'); $created = true; $pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]); $restored = DB::connection('upgrade_restore'); if ($fingerprint($restored) !== $before || $restored->table('migrations')->count() !== $migrationCount || $restored->getSchemaBuilder()->hasTable('quotation_exchange_rates') || $restored->getSchemaBuilder()->hasColumn('supplier_bank_details', 'account_key') || $restored->getSchemaBuilder()->hasColumn('quotations', 'exchange_basis')) { throw new RuntimeException('Restauro anterior não recupera exactamente a base sintética anterior à actualização.'); } echo json_encode(['synthetic_upgrade_preserved_tables' => count($before), 'migration_delta' => 2, 'new_values_empty' => true, 'replay_no_changes' => true, 'synthetic_backup_restore_verified' => true, 'pre_upgrade_restore_verified' => true, 'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $dump)], JSON_THROW_ON_ERROR).PHP_EOL; } finally { DB::purge('upgrade_restore'); if ($created) { $admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)'); echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL; } }