new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$database, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); $admin = $connect('postgres', $settings['DB_USERNAME'], $settings['DB_PASSWORD']); $id = bin2hex(random_bytes(6)); $role = 'compras_replenish_app_'.$id; $database = 'compras_replenish_restore_'.$id; $password = bin2hex(random_bytes(32)); $createdRole = $createdDatabase = false; $copy = null; try { $admin->exec('CREATE ROLE "'.$role.'" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS PASSWORD '.$admin->quote($password)); $createdRole = true; $admin->exec('CREATE DATABASE "'.$database.'" OWNER "'.$role.'"'); $createdDatabase = true; $process = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--no-owner', '--no-acl', '--exit-on-error', '--dbname='.$database, $directory.'/before.dump'], $root, ['PGHOST' => '127.0.0.1', 'PGPORT' => $source['DB_PORT'], 'PGUSER' => $role, 'PGPASSWORD' => $password], timeout: 120); $process->run(); if (! $process->isSuccessful()) { throw new LogicException('Private replenishment backup restore failed.'); } $copy = $connect($database, $role, $password); $copy->exec('SET default_transaction_read_only=on'); $baseline = json_decode(file_get_contents($directory.'/baseline.private.json'), true, 32, JSON_THROW_ON_ERROR); $tables = $copy->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN); if ($tables !== array_keys($baseline)) { throw new LogicException('Restored table inventory differs.'); } foreach ($baseline as $table => $before) { $rows = $copy->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN); if (count($rows) !== $before['rows'] || ! hash_equals($before['sha256'], hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)))) { throw new LogicException('Restored replenishment backup data differs.'); } } $result = ['date' => gmdate('c'), 'state' => 'passed', 'restored_tables_identical' => count($baseline), 'source_database_or_settings_changed' => false, 'business_commands' => false]; } finally { $copy = null; if ($createdDatabase) { $admin->exec('DROP DATABASE "'.$database.'" WITH (FORCE)'); } if ($createdRole) { $admin->exec('DROP ROLE "'.$role.'"'); } } $result['temporary_database_and_role_removed'] = true; file_put_contents($root.'/docs/proofs/replenishment-task-recovery.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL); echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;