54 lines
1.7 KiB
PHP
54 lines
1.7 KiB
PHP
<?php
|
|
/**
|
|
* 为 dice_player 增加 (dept_id, username) 唯一索引
|
|
* 用法:在 server 目录执行 php db/run_dice_player_dept_username_unique.php
|
|
*/
|
|
declare(strict_types=1);
|
|
|
|
define('BASE_PATH', dirname(__DIR__));
|
|
|
|
require_once BASE_PATH . '/vendor/autoload.php';
|
|
|
|
if (class_exists(\Dotenv\Dotenv::class) && is_file(BASE_PATH . '/.env')) {
|
|
if (method_exists(\Dotenv\Dotenv::class, 'createUnsafeMutable')) {
|
|
\Dotenv\Dotenv::createUnsafeMutable(BASE_PATH)->load();
|
|
} else {
|
|
\Dotenv\Dotenv::createMutable(BASE_PATH)->load();
|
|
}
|
|
}
|
|
|
|
\Webman\Config::load(BASE_PATH . '/config', ['route', 'plugin']);
|
|
\Webman\ThinkOrm\ThinkOrm::start(null);
|
|
|
|
use support\think\Db;
|
|
|
|
echo "检查 (dept_id, username) 重复...\n";
|
|
$dupes = Db::query(
|
|
'SELECT dept_id, username, COUNT(*) AS c FROM dice_player
|
|
WHERE username IS NOT NULL AND username <> \'\'
|
|
GROUP BY dept_id, username HAVING c > 1 LIMIT 20'
|
|
);
|
|
if (!empty($dupes)) {
|
|
echo "存在重复记录,请先处理后再执行:\n";
|
|
print_r($dupes);
|
|
exit(1);
|
|
}
|
|
|
|
$indexes = Db::query("SHOW INDEX FROM `dice_player` WHERE Key_name = 'idx_dice_player_username'");
|
|
if (!empty($indexes)) {
|
|
Db::execute('ALTER TABLE `dice_player` DROP INDEX `idx_dice_player_username`');
|
|
echo "已删除 idx_dice_player_username\n";
|
|
}
|
|
|
|
$uk = Db::query("SHOW INDEX FROM `dice_player` WHERE Key_name = 'uk_dice_player_dept_username'");
|
|
if (empty($uk)) {
|
|
Db::execute(
|
|
'ALTER TABLE `dice_player` ADD UNIQUE INDEX `uk_dice_player_dept_username` (`dept_id`, `username`)'
|
|
);
|
|
echo "已创建 uk_dice_player_dept_username\n";
|
|
} else {
|
|
echo "uk_dice_player_dept_username 已存在,跳过\n";
|
|
}
|
|
|
|
echo "完成\n";
|