61 lines
2.5 KiB
PHP
61 lines
2.5 KiB
PHP
<?php
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
function fix_table($pdo, $table_name, $fk_name) {
|
|
echo "--- Processing table: {$table_name} ---\\n";
|
|
|
|
// Check and add column
|
|
$res = $pdo->query("SHOW COLUMNS FROM `{$table_name}` LIKE 'client_id'");
|
|
if ($res->rowCount() == 0) {
|
|
echo "Adding client_id to {$table_name}...\\n";
|
|
$pdo->exec("ALTER TABLE `{$table_name}` ADD COLUMN `client_id` INT NOT NULL DEFAULT 1");
|
|
} else {
|
|
echo "client_id already exists in {$table_name}. Setting to default...\\n";
|
|
// This handles cases where the column was added but not populated correctly
|
|
$pdo->exec("UPDATE `{$table_name}` SET `client_id` = 1 WHERE `client_id` = 0 OR `client_id` IS NULL");
|
|
}
|
|
|
|
// Check and add foreign key
|
|
$res = $pdo->query("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '{$table_name}' AND COLUMN_NAME = 'client_id' AND REFERENCED_TABLE_NAME = 'clients'");
|
|
if ($res->rowCount() == 0) {
|
|
echo "Adding foreign key to {$table_name}...\\n";
|
|
try {
|
|
$pdo->exec("ALTER TABLE `{$table_name}` ADD CONSTRAINT `{$fk_name}` FOREIGN KEY (`client_id`) REFERENCES `clients`(`id`) ON DELETE CASCADE");
|
|
} catch (PDOException $e) {
|
|
// If the constraint somehow exists with a different name, this might fail.
|
|
echo "Could not add foreign key to {$table_name}. It might already exist with a different name. Error: " . $e->getMessage() . "\\n";
|
|
}
|
|
} else {
|
|
echo "Foreign key on {$table_name}.client_id already exists.\\n";
|
|
}
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
fix_table($pdo, 'users', 'fk_users_client_id');
|
|
fix_table($pdo, 'macro_areas', 'fk_macro_areas_client_id');
|
|
fix_table($pdo, 'budgets', 'fk_budgets_client_id');
|
|
fix_table($pdo, 'expenses', 'fk_expenses_client_id');
|
|
|
|
// Mark migrations as executed to prevent them from running again
|
|
$migrations_to_mark = [
|
|
'006_add_client_id_to_users.sql',
|
|
'007_add_client_id_to_macro_areas.sql',
|
|
'008_add_client_id_to_budgets.sql',
|
|
'009_add_client_id_to_expenses.sql'
|
|
];
|
|
|
|
$stmt = $pdo->prepare("INSERT IGNORE INTO migrations (migration_name) VALUES (:migration_name)");
|
|
foreach ($migrations_to_mark as $migration_name) {
|
|
echo "Marking migration {$migration_name} as executed...\\n";
|
|
$stmt->execute(['migration_name' => $migration_name]);
|
|
}
|
|
|
|
echo "\\nSchema fix script finished.\\n";
|
|
|
|
} catch (PDOException $e) {
|
|
die("Error fixing schema: " . $e->getMessage());
|
|
}
|
|
|