Je devais changer les collates de toutes les bases de données, tables et colonnes dans un cluster avec de nombreuses bases.
J'ai utilisé un script fonctionnant sous php 8.1 et mysql 8.0.
function changeCollate() {
$databases = $this->fetchQueryToArray("SHOW DATABASES LIKE 'nova_%'")->rows;
foreach ($databases as $value) {
$db = $value['Database (nova_%)'];
$this->LOG("-- banco de dados --- " . $db);
$this->exeQuery("ALTER DATABASE `$db` COLLATE utf8mb4_0900_ai_ci;");
$this->exeQuery("use $db");
$tables = $this->fetchQueryToArray("SHOW tables")->rows;
foreach ($tables as $table) {
$tb_name = $table["Tables_in_$db"];
$this->exeQuery("ALTER TABLE `$tb_name` COLLATE utf8mb4_0900_ai_ci;");
$QUERY = "ALTER TABLE `$db`.`$tb_name`\n";
$columns = $this->fetchQueryToArray("SHOW FULL COLUMNS FROM $tb_name WHERE Type LIKE 'varchar%' OR Type = 'text' OR Type like 'enum%' OR Type = 'longtext' OR Type = 'mediumtext'")->rows;
foreach ($columns as $column) {
$QUERY .= "CHANGE `{$column['Field']}` `{$column['Field']}` {$column['Type']} COLLATE 'utf8mb4_0900_ai_ci'";
$QUERY .= ($column['Null'] == 'YES') ? " NULL" : " NOT NULL";
if ($column['Default']) $QUERY .= " DEFAULT '{$column['Default']}'";
if ($column['Comment']) $QUERY .= " COMMENT '{$column['Comment']}'";
$QUERY .= ",\n";
}
if ($QUERY == "ALTER TABLE `$db`.`$tb_name`\n") continue;
$QUERY = substr($QUERY, 0, -2) . ";\n\n";
$this->exeQuery($QUERY);
}
}
}
4 votes
La réponse se trouve ici : stackoverflow.com/questions/5906585/