2026-08-20-01-add-orders-index.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. declare(strict_types=1);
  3. // Beispielmigration mit Datenbank.
  4. //
  5. // $context["pdo"] ist die Verbindung aus MANAGE_BACKUP_DATABASE.
  6. // Idempotent: prüft erst, ob der Index bereits existiert. MySQL kennt kein
  7. // "ADD INDEX IF NOT EXISTS", deshalb die Abfrage über information_schema.
  8. return function (array $context): void {
  9. if (!isset($context["pdo"])) {
  10. throw new RuntimeException(
  11. "Diese Migration benötigt eine Datenbank. MANAGE_BACKUP_DATABASE ist nicht konfiguriert.",
  12. );
  13. }
  14. /** @var PDO $pdo */
  15. $pdo = $context["pdo"];
  16. $statement = $pdo->prepare(
  17. "SELECT COUNT(*) FROM information_schema.statistics
  18. WHERE table_schema = DATABASE()
  19. AND table_name = :table
  20. AND index_name = :index",
  21. );
  22. $statement->execute(["table" => "orders", "index" => "idx_orders_created"]);
  23. if ((int) $statement->fetchColumn() > 0) {
  24. return;
  25. }
  26. $pdo->exec("ALTER TABLE orders ADD INDEX idx_orders_created (created_at)");
  27. };