СЛЕДУЮЩИЙ ОТВЕТ ИСПОЛЬЗУЕТ PHP , Я оставляю его здесь для будущих пользователей.
Я специально написал код для этого (в PHP):
<code>$db = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$allTables = Array
(
//put all table names in this array
);
foreach($allTables as $tbl){
define($tbl, $tbl);
}
$clm = '$columns';
$inds = '$indexes';
$query = "SHOW TABLES IN {$dbname}";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_{$dbname}"];
}
//TO GET ARRAY FOR TABLE DISPLAY:
$cols = array();
foreach($tables as $tbl){
// echo "<br/>".
$query = "SHOW COLUMNS FROM $tbl";
$cols[$tbl] = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$cols[$tbl][] = array('Field'=>$row['Field'],
'Type'=>$row['Type'],
'Null'=>$row['Null'],
'Default'=>$row['Default'],
'Extra'=>$row['Extra'],
);
}
}
$index = array();
$query = "SELECT * FROM information_schema.statistics
WHERE TABLE_SCHEMA = '{$dbname}';
";
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$index[$row['TABLE_NAME']][] = array('INDEX_NAME'=>$row['INDEX_NAME'],
'COLUMN_NAME'=>$row['COLUMN_NAME'],
'INDEX_TYPE'=>$row['INDEX_TYPE'],
'INDEX_NAME'=>$row['INDEX_NAME'],
'SEQ_IN_INDEX'=>$row['SEQ_IN_INDEX'],
);
}
//echo "<pre>";print_r($index);
//exit;
//TO GET THE ARRAY VARIABLE
echo "<pre>
<?php
$clm = Array (";
foreach ($cols as $key=>$tbl){
echo "
$key => Array (";
foreach($tbl as $col){
echo "
Array ( ";
foreach($col as $k=>$val){
echo "
'$k' => \"$val\",";
}
echo "
),";
}
echo "
),";
}
echo "
);";
echo "
"; echo"
$inds = Array (";
foreach ($index as $key=>$tbl){
echo "
$key => Array (";
foreach($tbl as $col){
echo "
Array ( ";
foreach($col as $k=>$val){
echo "
'$k' => \"$val\",";
}
echo "
),";
}
echo "
),";
}
echo "
);
?>";
echo "
";
Вставьте результат в файл php (называемый currentDB.php
).
Затем в другом файле, гдесоздание происходит с файлом, который вы создали:
<code>define('BY_COL', 'column');
define('BY_IND', 'index');
$allTables = Array
(
//put all table names in this array
);
foreach($allTables as $tbl){
define($tbl, $tbl);
}
include_once 'currentDB.php';
$query = "SHOW TABLES IN $dbname";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_$dbname"];
}
$checkTables = checkTables($tables);
echo "THE FOLLOWING TABLES <b>ARE</b> IN THE DB: <br />
<pre>";print_r(array_diff($allTables,$checkTables));echo "
"; if ($ checkTables) {echo" СЛЕДУЮЩИЕ ТАБЛИЦЫ
НЕ В БД:". //"
";print_r($checkTables);echo "
";" "; createTables ($ checkTables); $ query =" ПОКАЗАТЬ ТАБЛИЦЫ В $ dbname "; $ tables = array (); $ result = mysql_query ($ query) или die (" ERROR ONE: ". mysql_error ()); while ($ row = mysql_fetch_array ($ result)) {$ tables [] = $ row ["Tables_in_ $ dbname"];}} // ПОЛУЧИТЬ Массив для отображения таблицы: $ cols = array (); foreach ($ tablesкак $ tbl) {// echo "". $ query =" ПОКАЗАТЬ КОЛОННЫ ИЗ $ tbl "; $ cols [$ tbl] = array (); $ result = mysql_query ($ query) или die (" ERROR ONE: ". mysql_error ()); while ($ row= mysql_fetch_array ($ result)) {$ cols [$ tbl] [] = array ('Field' => $ row ['Field'], 'Type' => $ row ['Type'], 'Null' =>$ row ['Null'], 'Default' => $ row ['Default'], 'Extra' => $ row ['Extra'],);}} $ checkTables = checkCols ($ cols); if ($checkTables) {echo "СЛЕДУЮЩИЕ COLS
РАЗНЫЕ В БД:". //"
";print_r($checkTables);echo "
"." "; alterTable ($ checkTables);} $ index = array (); $ query =" SELECT * FROM information_schema.statistics WHERE TABLE_SCHEMA = '$ dbname';"; $ result = mysql_query ($ query) или die (" ERROR ONE: ". mysql_error ()); while ($ row = mysql_fetch_array ($ result)) {$ index [$ row ['TABLE_NAME']] [] =массив ('INDEX_NAME' => $ row ['INDEX_NAME'], 'COLUMN_NAME' => $ row ['COLUMN_NAME'], 'INDEX_TYPE' => $ row ['INDEX_TYPE'], 'INDEX_NAME' => $ row ['INDEX_NAME '],' SEQ_IN_INDEX '=> $ row [' SEQ_IN_INDEX '],);} $ checkTables = checkIndexes ($ index); if ($ checkTables) {echo "СЛЕДУЮЩИЕ ИНДЕКСЫ
РАЗЛИЧНЫ * ВDB:". //"
";print_r($checkTables);echo "
"." "; alterTable ($ checkTables, BY_IND);} // echo"
";print_r($indexes);echo "
"; function checkTables ($ array) {$ tbls = $ GLOBALS ['allTables']; $ diff = array_diff ($ tbls, $ array); if ($ diff) {return $ diff;} return array ();} функцияcheckCols ($ array) {$ cols = $ GLOBALS ['columns']; $ diff = array_diff_no_cast ($ cols, $ array); if ($ diff) {// echo "HI"; return $ diff;} return array ();} функция checkIndexes ($ array) {$ ind = $ GLOBALS ['indexes']; $ diff = array_diff_no_cast ($ ind, $ array); if ($ diff) {// echo "HI"; return $ diff;} return array ();} функция createTables ($ tables) {$ cols = $ GLOBALS ['columns']; $ ind = $ GLOBALS ['indexes']; foreach ($ таблицы как $ t){$ thisCols = (isset ($ cols [$ t])? $ cols [$ t]: array ()); $ thisInd = (isset ($ ind [$ t])? fromIndex ($ ind [$ t]): array ()); $ create = "CREATE TABLE` $ t` (\ n "; foreach ($ thisCols as $ k => $ c) {// echo"
$k\n{$c['Default']}
"; if ($ c ['Default)'] ==' CURRENT_TIMESTAMP ') {// echo "IN HERE"; $ c [' Extra '] = "ON UPDATE CURRENT_TIMESTAMP";} $ create. = "` {$ C [' Field ']} `{$c ['Type']} ". (($ c ['Null'] == 'NO')? 'NOT NULL': '')." ". ((strlen ($ c ['Default']))>0)? "DEFAULT". (Is_quoted ($ c ['Default'])? "'{$ C [' Default ']}'": "{$ c ['Default']}"): '')."{$ c ['Extra']}"; if (count ($ thisCols)! == ($ k + 1)) {$ create. = ", \ n";} else $ create. = "\ n";} $ i = 0; foreach ($ thisInd как $ k => $ c) {if ($ i == 0) {$ create. = ", \ n";}if ($ c ['INDEX_NAME'] == 'PRIMARY') {$ create. = "PRIMARY";} else {$ iName = explode ("_", $ c ['INDEX_NAME']);if (array_search ("UNIQUE", $ iName)) {$ create. = "UNIQUE";}} $ create. = "KEY".(($ c ['INDEX_NAME'] == 'PRIMARY')? '': "` {$ c ['INDEX_NAME']} `"). "({$ c ['COLUMN_NAME']}))";if (count ($ thisInd)! == ($ i + 1)) {$ create. = ", \ n";} else $ create. = "\ n";// echo "
";print_r($c);echo "
";$ Я ++;} $ create. = ");";// echo "
$create
";mysql_query ($ create) или die ("ERROR CREATE:". mysql_error ());echo "СОЗДАН $ t";} // die;} функция fromIndex ($ ind) {$ return = array (); foreach ($ ind as $ i) {$ return [$ i ['INDEX_NAME']] ['INDEX_NAME'] = $ i['INDEX_NAME']; // echo $ i ['COLUMN_NAME']. "-". $ return [$ i ['INDEX_NAME']] ['COLUMN_NAME'] = (isset ($ return [$ i ['INDEX_NAME']] ['COLUMN_NAME'])?" {$ return [$ i ['INDEX_NAME']] [' COLUMN_NAME ']}, `{$ i [' COLUMN_NAME ']}` ":" `{{$ i [' COLUMN_NAME ']}` ");} // echo"
";print_r($return);echo "
"; //die; return $ return;} функция alterTable ($ table, $ type = BY_COL) {// echo "
"; switch ($ type) {case BY_COL: // echo BY_COL; $ tbls = $ GLOBALS ['cols']; $ realTbls = $ GLOBALS [' columns ']; // echo "";print_r($table);echo""; // die; foreach ($ table as $ k => $ t) {// echo // $ query = "SHOWКОЛОННЫ ОТ $ k "; // echo""; foreach ($ t as $ ky => $ col) {// echo if ($ ky == 0) {$ after = 'FIRST';} else {$ after =" ПОСЛЕ `{$ realTbls [$ k][$ ky-1] ['Field']} `";} $ primary = false; if ($ col ['Default'] == 'CURRENT_TIMETAMP') {$ col ['Extra']. = "ON UPDATE CURRENT_TIMESTAMP";} if ($ col ['Extra'] == 'auto_increment') {$ query2 =" ALTER TABLE `$ k` ADD PRIMARY KEY (` {$ col ['Field']} `)"; $ query3 ="ALTER TABLE` $ k` CHANGE COLUMN `{$ col ['Field']}` `{$ col ['Field']}` {$ col ['Type']} ". ($ Col ['Null']== 'YES'? 'NULL': 'NOT NULL'). ((! Empty ($ col ['Default']))? 'DEFAULT'. (Is_quoted ($ col ['Default'])? "'{$ col ['Default']} '": $ col [' Default ']):' ')." {$ col [' Extra ']} "." $ after; "; $ primary = true; $ col ['Extra'] = "";} // echo $ query = "ALTER TABLE` $ k` ". (Field_in_array ($ tbls [$ k], $ col ['Field'])?" CHANGE COLUMN `{$ col['Field']} `": "ADD COLUMN"). "` {$ Col ['Field']} `{$ col ['Type']}". ($ Col ['Null'] == 'YES'?' NULL ':' NOT NULL '). ((! Empty ($ col [' Default ']))?' DEFAULT '. (Is_quoted ($ col [' Default '])? "' {$ Col ['По умолчанию ']}' ": $ col ['По умолчанию']): '')." {$ Col ['Extra']}»."$ after;";// эхо ""; mysql_query ($ query) или die (" ERROR CREATE: $ query ".mysql_error ()); if ($ primary) {mysql_query ($ query2) или die (" ERROR CREATE: $ query2 ".mysql_error ());mysql_query ($ query3) или die ("ERROR CREATE: $ query3" .mysql_error ());} echo "ADDED $ k: {$ col ['Field']}"; echo "";} // if ($ k == 'session') {// echo" $ky:\n";print_r($tbls[$k]);die;
// }
}
break;
case BY_IND:
// echo BY_IND;
$tbls = $GLOBALS['index'];
foreach($table as $k=>$t){
$addTbls= fromIndex($table[$k]);
$thisInd = (isset($tbls[$k])?fromIndex($tbls[$k]):array());
// echo "<pre>$k:\n";print_r($addTbls);
foreach($addTbls as $added){
$beg = "INDEX";
if($added['INDEX_NAME']=='PRIMARY'){
$beg = "PRIMARY KEY";
$added['INDEX_NAME'] = '';
}
else{
$iName = explode("_",$added['INDEX_NAME']);
if(array_search("UNIQUE",$iName)){
$beg = "UNIQUE ".$beg;
}
}
// echo
$query = "ALTER TABLE `$k` ".(field_in_array($thisInd,$added['INDEX_NAME'],'INDEX_NAME')?"DROP INDEX `{$added['INDEX_NAME']}`, ":'')."ADD $beg `{$added['INDEX_NAME']}` ({$added['COLUMN_NAME']})";
mysql_query($query) or die("ERROR CREATE:".mysql_error());
echo "ADDED $k: {$added['INDEX_NAME']}";
echo "<br />";
}
}
// die;
break;
}
// echo "</u><br />";
}
function is_quoted($str){
if(is_numeric($str))
return false;
if($str == 'CURRENT_TIMESTAMP')
return false;
return true;
}
function field_in_array($arr, $field, $type = 'Field'){
foreach($arr as $val){
// echo "HERE: $field, $type";
// print_r($val);echo "<br/>";
if($val[$type]==$field){
// echo "HI";
return true;
}
}
return false;
}
##################################
# FUNCTION - multidim diff #
##################################
function array_diff_no_cast(&$ar1, &$ar2) {
$diff = Array();
foreach ($ar1 as $key => $val1) {
foreach($val1 as $k=>$val2){
if (!isset($ar2[$key]) || array_search($val2, $ar2[$key]) === false) {
$diff[$key][$k] = $val2;
}
}
}
return $diff;
}
</code>