make(Kernel::class)->bootstrap(); $owner = DB::connection('pgsql')->getConfig(); unset($owner['name']); if ($owner['host'] !== '127.0.0.1') { throw new LogicException('Administrative server must be local.'); } $qa = [...$owner, 'url' => null, 'host' => $s['DB_HOST'], 'database' => $s['DB_DATABASE'], 'username' => $s['DB_USERNAME'], 'password' => $s['DB_PASSWORD']]; config(['database.connections.approval_install' => $qa, 'database.connections.approval_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]); DB::setDefaultConnection('approval_install'); $db = DB::connection(); $admin = DB::connection('approval_owner'); $identity = $db->selectOne('select current_database() as db, current_user as role'); if ($identity->db !== $s['DB_DATABASE'] || $identity->role !== $s['DB_USERNAME']) { throw new LogicException('Effective database identity mismatch.'); } $schema = $db->getSchemaBuilder(); if ($schema->hasColumn('tenants', 'requisition_approval_policy') || $schema->hasColumn('approval_steps', 'routing')) { throw new LogicException('Schema already present; do not reapply.'); } $tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename'); $columns = $keys = []; foreach ($tables as $table) { $columns[$table] = $schema->getColumnListing($table); $keys[$table] = $schema->getForeignKeys($table); } $fingerprint = static function ($connection) use ($columns): array { $out = []; foreach ($columns as $table => $names) { $selected = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names)); $rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text'); $out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR)); } return $out; }; $pg = static function ($binary, array $args, array $connection): void { $process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $connection['host'], 'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120); $process->run(); if (! $process->isSuccessful()) { throw new RuntimeException('Backup/restore failed; do not install.'); } }; $directory = 'C:/laragon/data/sgf-tempo/backups/compras-approval-search-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3)); if (! mkdir($directory, 0700, true) || file_put_contents($directory.'/settings.before.json', $settingsBytes) !== strlen($settingsBytes) || ! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) { throw new RuntimeException('Could not preserve deployment state.'); } $dump = $directory.'/before.dump'; $restore = 'compras_pilot_restore_'.bin2hex(random_bytes(6)); $created = false; $migrateAndCheck = static function ($connection, string $name, array $baseline, int $migrationCount) use ($migration, $fingerprint, $keys): void { $previous = DB::getDefaultConnection(); DB::setDefaultConnection($name); try { if (Artisan::call('migrate', ['--database' => $name, '--path' => [$migration], '--force' => true]) !== 0) { throw new RuntimeException('Exact migration failed.'); } $after = $fingerprint($connection); unset($after['migrations'], $baseline['migrations']); if ($after !== $baseline || $connection->table('migrations')->count() !== $migrationCount + 1 || $connection->table('tenants')->whereNotNull('requisition_approval_policy')->exists() || $connection->table('approval_steps')->whereNotNull('routing')->exists()) { throw new LogicException('Old data changed or new columns are not empty.'); } foreach ($keys as $table => $expected) { if ($connection->getSchemaBuilder()->getForeignKeys($table) !== $expected) { throw new LogicException('Foreign keys changed.'); } } } finally { DB::setDefaultConnection($previous); } }; try { $db->beginTransaction(); $db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); $baseline = $fingerprint($db); $migrationCount = $db->table('migrations')->count(); $snapshot = $db->selectOne('select pg_export_snapshot() as snapshot')->snapshot; $pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$qa['database']], $qa); $db->commit(); $admin->statement('CREATE DATABASE "'.$restore.'" OWNER "'.$s['DB_USERNAME'].'"'); $created = true; $pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump], $qa); config(['database.connections.approval_restore' => [...$qa, 'database' => $restore]]); $restored = DB::connection('approval_restore'); if ($fingerprint($restored) !== $baseline) { throw new LogicException('Same-role restore differs from backup snapshot.'); } $migrateAndCheck($restored, 'approval_restore', $baseline, $migrationCount); $db->transaction(function () use ($db, $tables, $baseline, $fingerprint, $migrateAndCheck, $migrationCount, $settingsHash, $settingsFile) { $db->statement("SET LOCAL lock_timeout = '5s'"); foreach ($tables as $table) { $db->statement('LOCK TABLE "'.$table.'" IN SHARE MODE'); } if ($fingerprint($db) !== $baseline || hash_file('sha256', $settingsFile) !== $settingsHash) { throw new LogicException('Pilot changed after backup; installation refused.'); } $migrateAndCheck($db, 'approval_install', $baseline, $migrationCount); }); $result = ['environment' => 'http://127.0.0.1:8005', 'schema_installed' => true, 'capabilities_enabled' => false, 'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'settings_backup' => $directory.'/settings.before.json', 'restored_tables_checked' => count($tables), 'previous_business_tables_preserved' => count($tables) - 1, 'same_restore_role' => true, 'foreign_keys_preserved' => true, 'new_values_null' => true, 'migration_delta' => 1, 'assets_verified' => count($assets), 'manifest_sha256' => $authorization['manifest_sha256'], 'business_commands' => false, 'grants_changed' => false]; file_put_contents($proof, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL); if (hash_file('sha256', $settingsFile) !== $settingsHash) { throw new LogicException('Settings changed before activation; schema retained, capabilities not enabled.'); } $after = [...$s, $flagNames[0] => 'true', $flagNames[1] => 'true']; $protected = $after; foreach ($flagNames as $flag) { unset($protected[$flag]); } $beforeProtected = $s; foreach ($flagNames as $flag) { unset($beforeProtected[$flag]); } if ($protected !== $beforeProtected) { throw new LogicException('Unrelated deployment settings changed.'); } $temporary = $settingsFile.'.approval-search.tmp'; $bytes = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL; if (file_put_contents($temporary, $bytes) !== strlen($bytes) || ! rename($temporary, $settingsFile)) { throw new RuntimeException('Could not atomically activate approved capabilities.'); } $result['capabilities_enabled'] = json_decode(file_get_contents($settingsFile), true, 32, JSON_THROW_ON_ERROR) === $after; $result['other_settings_preserved'] = true; $result['changed_settings'] = $flagNames; } finally { if ($db->transactionLevel() > 0) { $db->rollBack(); } DB::purge('approval_restore'); if ($created) { $admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)'); } } $result['restore_database_removed'] = true; file_put_contents($proof, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL); echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;