Skip to content

Instantly share code, notes, and snippets.

@selva987
Last active May 11, 2023 09:48
Show Gist options
  • Save selva987/d3ba384e5c1f5753939eafe5f8dd78aa to your computer and use it in GitHub Desktop.
Save selva987/d3ba384e5c1f5753939eafe5f8dd78aa to your computer and use it in GitHub Desktop.
Remove all zerofills from MYSQL database
<?php
/**
* This script scans the provided database schemas and generates necesary DDL to remove
* zerofill property from table columns
*
* This code is provided as is, I'm not responsible for any data loss
* Review the output before executing it on your DB
* Of course, backup your DB first because, you know, sh*t happens
*/
//Connection parameters
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$port = '3306';
//End of line for CLI
//$eol = PHP_EOL;
//End of line for browsers
$eol = '<br>';
if(!$mysql = mysqli_connect($host, $user, $pass, '', $port)) {
die('Cant connect to DB. ' . mysqli_error($mysql));
}
//Set here the schemas you want to scan
$schemas = [
'schema_1',
'schema_2',
];
foreach ($schemas as $s) {
echo "/*********$s schema**********/$eol";
$tableQuery = $mysql->query("SHOW TABLES FROM $s");
while ($t = $tableQuery->fetch_array(MYSQLI_NUM)) {
$tableFullname = "`$s`.`$t[0]`";
$columnQuery = $mysql->query("SHOW FULL COLUMNS FROM $tableFullname");
while ($c = $columnQuery->fetch_object()) {
if(strstr($c->Type, 'zerofill') !== false) {
echo getAlter($tableFullname, $c) . $eol;
}
}
}
}
function getAlter($table, $col) {
$newType = str_replace('zerofill', '', $col->Type);
return "ALTER TABLE $table MODIFY COLUMN $col->Field $newType $col->Extra " . ($col->Null === 'NO' ? 'NOT' : '')
. " NULL " . ($col->Default !== null ? "DEFAULT $col->Default" : "") . " "
. ($col->Comment ? "COMMENT '$col->Comment'" :"") . ";";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment