Files
tinker_tickets/migrations/run_migrations.php

108 lines
2.5 KiB
PHP
Raw Normal View History

2026-01-01 15:40:32 -05:00
<?php
/**
* Database Migration Runner
* Executes all migration files in order
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Load environment variables
$envFile = dirname(__DIR__) . '/.env';
if (!file_exists($envFile)) {
die("Error: .env file not found at $envFile\n");
}
$envVars = parse_ini_file($envFile);
if (!$envVars) {
die("Error: Could not parse .env file\n");
}
// Connect to database
$conn = new mysqli(
$envVars['DB_HOST'],
$envVars['DB_USER'],
$envVars['DB_PASS'],
$envVars['DB_NAME']
);
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error . "\n");
}
echo "Connected to database: {$envVars['DB_NAME']}\n\n";
// Get all migration files
$migrationFiles = glob(__DIR__ . '/*.sql');
sort($migrationFiles);
// Filter out rollback script
$migrationFiles = array_filter($migrationFiles, function($file) {
return !strpos($file, 'rollback');
});
if (empty($migrationFiles)) {
echo "No migration files found.\n";
exit(0);
}
echo "Found " . count($migrationFiles) . " migration(s):\n";
foreach ($migrationFiles as $file) {
echo " - " . basename($file) . "\n";
}
echo "\n";
// Execute each migration
$successCount = 0;
$errorCount = 0;
foreach ($migrationFiles as $file) {
$filename = basename($file);
echo "Executing: $filename... ";
$sql = file_get_contents($file);
// Split SQL into individual statements
// This handles multi-statement migrations
if ($conn->multi_query($sql)) {
do {
// Store first result set
if ($result = $conn->store_result()) {
$result->free();
}
// Check for errors
if ($conn->errno) {
echo "FAILED\n";
echo " Error: " . $conn->error . "\n";
$errorCount++;
break;
}
} while ($conn->more_results() && $conn->next_result());
// If we got through all results without error
if (!$conn->errno) {
echo "OK\n";
$successCount++;
}
} else {
echo "FAILED\n";
echo " Error: " . $conn->error . "\n";
$errorCount++;
}
}
echo "\n";
echo "Migration Summary:\n";
echo " Success: $successCount\n";
echo " Errors: $errorCount\n";
if ($errorCount > 0) {
echo "\nSome migrations failed. Please review errors above.\n";
exit(1);
} else {
echo "\nAll migrations completed successfully!\n";
exit(0);
}
$conn->close();