This repository has been archived by the owner on Jul 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
MySQLDiff.class.php
416 lines (305 loc) · 12.5 KB
/
MySQLDiff.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<?php
/**
* MySQLDiff
*
* @package MySQLDiff
* @author Nabeel Shahzad <https://github.com/nshahzad/MySQLDiff>
*/
class MySQLDiff {
public $xml_errors = array();
public $sql_errors = array();
protected $params;
protected $db;
protected $xml;
protected $missingCols = array();
/**
* MySQLDiff::construct()
*
* @param mixed $params
* @return
*/
public function __construct($params) {
if(!is_array($params)) {
throw new Exception("Invalid parameters passed");
return false;
}
$this->params = array_merge(array(
'dbuser' => '',
'dbpass' => '',
'dbname' => '',
'dbhost' => '',
'dumpxml' => '',
), $params);
# Connect to MySQL
$this->db = mysql_connect(
$this->params['dbhost'],
$this->params['dbuser'],
$this->params['dbpass'],
true
);
if(!$this->db) {
throw new Exception("Could not connect to {$this->params['dbuser']}@{$this->params['dbserver']}");
return false;
}
if(!mysql_select_db($this->params['dbname'], $this->db)) {
throw new Exception("Could not select database {$this->params['dbname']}");
return false;
}
if(!file_exists($this->params['dumpxml'])) {
throw new Exception("XML File \"{$this->params['dumpxml']}\" does not exist!");
return false;
}
# Load the XML file
libxml_use_internal_errors (true);
$this->xml = simplexml_load_file($this->params['dumpxml']);
if($this->xml === false) {
#$this->xml_errors = implode("\n", libxml_get_errors());
throw new Exception ("Errors in XML File: {$this->xml_errors}");
return false;
}
}
/**
* Get a list of diffs, returns the table and fields within it
* which are missing
*
* @return array
*/
public function getDiffs() {
return $this->findDiffs();
}
/**
* Return MySQL queries to add the missing columns into the table
*
* @return void
*/
public function getSQLDiffs() {
$diffData = $this->findDiffs();
if(count($diffData) == 0) {
return $diffData;
}
$sqlList = array();
# Add tables...
foreach($diffData['tables'] as $table) {
if(count($table) == 0) { # This table exists...
continue;
}
$sql = array();
$sql[] = 'CREATE TABLE `'.$table['Name'].'` (';
$colList = array();
foreach($diffData['columns'][$table['Name']] as $column) {
$colList[] = $this->getColumnLine($column);
}
$sql[] = implode(',', $colList);
$sql[] = ')';
$sql[] = 'ENGINE = '.$table['Engine'];
$sql[] = 'AUTO_INCREMENT = '.$table['Auto_increment'];
$sql[] = 'COMMENT = \''.$table['Comment'].'\'';
$sql[] = 'COLLATE '.$table['Collation'];
# Remove it from the columns list
unset($diffData['columns'][$table['Name']]);
$sqlList[] = implode(' ',$sql).';';
}
# Now add columns....
foreach($diffData['columns'] as $tableName => $columnList) {
foreach($columnList as $columnName => $column) {
$sql = array();
$sql[] = 'ALTER TABLE `'.$tableName.'` ADD';
$sql[] = $this->getColumnLine($column);
if($column['prevField'] === null) {
$sql[] = 'FIRST'; # Insert at top of table
} else {
$sql[] = 'AFTER `'.$column['prevField'].'`';
}
$sqlList[] = trim(implode(' ', $sql)).';';
}
}
# ALTER TABLES for TYPES
foreach($diffData['types'] as $tableName => $columnList) {
foreach($columnList as $columnName => $column) {
$sql = array();
$sql[] = 'ALTER TABLE `'.$tableName.'` CHANGE';
$sql[] = '`'.$columnName.'`';
$sql[] = $this->getColumnLine($column['newtype']);
$sqlList[] = trim(implode(' ', $sql)).';';
}
}
# Now create the SQL for generating indexes
foreach($diffData['indexes'] as $tableName => $indexes) {
if(count($indexes) == 0) {
continue;
}
foreach($indexes as $index) {
$sqlList[] = $this->getIndexLine($index);
}
}
return $sqlList;
}
/**
* MySQLDiff::getColumnLine()
*
* @param mixed $column
* @return void
*/
protected function getColumnLine($column) {
$sql = array();
$sql[] = '`'.$column['Field'].'` '.$column['Type'];
# Is this column null?
if(strtolower(trim($column['Null'])) == 'no') {
$sql[] = 'NOT NULL';
} else {
$sql[] = 'NULL';
}
# Is there a default value?
if(isset($column['Default'])) {
$sql[] = 'DEFAULT \''.$column['Default'].'\'';
}
# Any extra stuffs?
if(isset($column['Extra'])) {
$sql[] = strtoupper(trim($column['Extra']));
}
if(isset($column['Key'])) {
$key = strtolower(trim($column['Key']));
if($key == 'pri') {
$sql[] = 'PRIMARY KEY';
}/* elseif($key =='uni') {
$sql[] = 'UNIQUE';
}*/
}
return implode(' ', $sql);
}
/**
* Create an ALTER TABLE to create indexes
*
* @param mixed $index
* @return
*/
protected function getIndexLine($index) {
$sql = array();
$sql[] = 'ALTER TABLE `'.$index['Table'].'` ADD';
if($index['Key_name'] == 'PRIMARY') {
$sql[] = 'PRIMARY KEY ('.$index['Column_name'].')';
} else {
if($index['Non_unique'] == '0') {
$sql[] = 'UNIQUE';
} else {
#$sql[] = $index['Index_type'];
if(strtolower(trim($index['Index_type'])) == 'fulltext') {
$sql[] = 'FULLTEXT';
}
}
$sql[] = 'INDEX ('.$index['Column_name'].')';
}
return implode(' ', $sql).';';
}
/**
* Generate diffs from MySQL and the XML file, and then apply them
*
* @return void
*/
public function runSQLDiff() {
$sqlList = $this->getSQLDiffs();
foreach ($sqlList as $sql) {
$res = mysql_query($sql, $this->db);
#if(!$res) {
# throw new Exception(mysql_errno().': '.mysql_error());
#}
if(mysql_errno() != 0) {
$this->sql_errors[] = array(
'sql' => $sql,
'errno' => mysql_errno(),
'error' => mysql_error()
);
}
}
return $sqlList;
}
/**
* MySQLDiff::findDiffs()
*
* @return void
*/
protected function findDiffs() {
$this->missingCols = array();
$this->missingCols['tables'] = array();
$this->missingCols['columns'] = array();
$this->missingCols['types'] = array();
$this->missingCols['indexes'] = array();
foreach($this->xml->database->table_structure as $table) {
$tableName = (string) $table['name'];
# Get a list of columns from this table...
$desc_result = mysql_query('DESCRIBE '.$tableName, $this->db);
# Make sure table exists...
$columns = array();
if(mysql_errno() == 1146) {
foreach($table->options->attributes() as $key => $value) {
$this->missingCols['tables'][$tableName][$key] = (string) $value;
}
} else {
# Get list of columns
while($column = mysql_fetch_object($desc_result)) {
$columns[] = $column;
}
}
/* loop through all the columns returned by the above query and all the columns
from the fields in the xml file, and make sure they all match up, with the
fieldlist from the xml being the "master" outside loop which it looks up against
*/
$prevField = null;
foreach($table->field as $field) {
$fieldName = strtolower(trim((string) $field['Field']));
$found = false;
foreach($columns as $column) {
if(strtolower(trim($column->Field)) == $fieldName) {
/* Check the column type, etc, see if those differ */
if((strtolower(trim($column->Type)) != (string) $field['Type'])
|| (strtolower(trim($column->Null)) != strtolower(trim((string) $field['Null'])))
|| (strtolower(trim($column->Default)) != strtolower(trim((string) $field['Default'])))
|| (strtolower(trim($column->Extra)) != strtolower(trim((string) $field['Extra'])))
) {
$this->missingCols['types'][$tableName][$fieldName]['oldtype'] = $column;
$this->missingCols['types'][$tableName][$fieldName]['newtype'] = $field;
}
$found = true;
break;
}
}
if($found == false) {
# Add all attributes in, but not as SimpleXML objects
$this->missingCols['columns'][$tableName][$fieldName] = array();
foreach($field->attributes() as $key => $value) {
$this->missingCols['columns'][$tableName][$fieldName][$key] = (string) $value;
}
# Also add the previous field, so we know where to place it...
$this->missingCols['columns'][$tableName][$fieldName]['prevField'] = $prevField;
}
$prevField = $fieldName;
}
# Find any missing indexes
$indexes = array();
$res = mysql_query('SHOW INDEXES IN '.$tableName);
if($res) {
while($index = mysql_fetch_object($res)) {
$indexes[] = $index;
}
}
foreach($table->key as $tablekey) {
$keyName = strtolower(trim($tablekey['Key_name']));
$found = false;
foreach($indexes as $index) {
if(strtolower(trim($index->Key_name)) == $keyName) {
$found = true;
break;
}
}
if($found == false) {
$this->missingCols['indexes'][$tableName][$keyName] = array();
foreach($tablekey->attributes() as $key => $value) {
$this->missingCols['indexes'][$tableName][$keyName][$key] = (string) $value;
}
$this->missingCols['indexes'][$tableName][$keyName]['table'] = $tableName;
}
}
}
return $this->missingCols;
}
}