38676-vm/db/migrate_user_resources.php
2026-03-06 10:07:39 +00:00

43 lines
1.6 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
$db = db();
try {
// 1. Create the user_resources table
$db->exec("CREATE TABLE IF NOT EXISTS user_resources (
user_id INT NOT NULL,
resource_id INT NOT NULL,
amount BIGINT UNSIGNED NOT NULL DEFAULT 0,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, resource_id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (resource_id) REFERENCES game_resources(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
echo "Table user_resources created (if it did not exist).\n";
// 2. Get all users and all resources
$users = $db->query("SELECT id FROM users")->fetchAll(PDO::FETCH_COLUMN);
$resources = $db->query("SELECT id, slug FROM game_resources")->fetchAll(PDO::FETCH_ASSOC);
if (empty($users) || empty($resources)) {
echo "No users or resources found to initialize.\n";
} else {
// 3. Initialize resources for each user
$stmt = $db->prepare("INSERT IGNORE INTO user_resources (user_id, resource_id, amount) VALUES (?, ?, ?)");
foreach ($users as $userId) {
foreach ($resources as $resource) {
$initialAmount = ($resource['slug'] === 'res_xp') ? 1 : 0;
$stmt->execute([$userId, $resource['id'], $initialAmount]);
}
}
echo "Resources initialized for " . count($users) . " users.\n";
}
echo "Migration completed successfully.\n";
} catch (PDOException $e) {
die("Migration failed: " . $e->getMessage() . "\n");
}