-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbiutils-update.php
executable file
·325 lines (309 loc) · 10.7 KB
/
dbiutils-update.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
<?php
// ###########################################################################
// dbutils.php: Utilities for PHP Database Development with MySQL
// ===========================================================================
// Version 2020-02-01. See README.md
// ###########################################################################
function updateDatabase($action = 'check', $newSchema = false) {
function applyChange($apply, $change) {
if ($apply) {
sqx($change); // can't return first
return 'Applying : ' . $change . "\r\n";
} else {
return $change . ";\r\n";
}
}
function describeColumn($data) {
$opts = explode(':', $data);
$typedata = explode('(', $opts[0]);
$type = strtolower($typedata[0]);
$sq = $opts[0];
if (''.@$opts[1] == 'NO') {
$sq .= ' NOT NULL';
}
$default = str_replace('~', ':', $opts[3]);
if (($type == 'varchar')
|| ($type == 'char')
|| ($type == 'date')
|| ($type == 'time')
|| ($type == 'datetime')
|| ($type == 'timestamp')
|| ($type == 'enum')
) {
$sq .= " DEFAULT '" . mes($default) . "'";
} elseif ($opts[3] != '') {
$sq .= ' DEFAULT ' . $default;
}
if ($opts[4] == 'auto_increment') {
$sq .= ' AUTO_INCREMENT';
}
return $sq;
}
$out = '';
$fdbname = sqf('SELECT database() AS dbname');
$dbname = ''.@(string)$fdbname['dbname'];
$qst = 'SHOW TABLES';
$tables = array();
$indices = array();
$struct = '';
$renameTables = array();
$renameContent = array();
while ($tab = sq($qst)) {
foreach ($tab as $k => $table) {
$qs = 'DESCRIBE `' . $table . '`';
$tables[$table] = array();
while ($fr = sq($qs)) {
$field = $fr['Field'];
$def = $fr['Type']
. ':' . $fr['Null'] . ':' . $fr['Key']
. ':' . str_replace(':', '~', $fr['Default']) . ':' . $fr['Extra'];
$tables[$table][$field] = $def;
$struct .= $table . ':' . $field . ':' . $def . "\r\n";
}
$qs = 'SHOW INDEXES FROM `' . $table . '`';
$keys = array();
$keyTypes = array();
while ($fx = sq($qs)) {
$keyname = $fx['Key_name'];
if (!isset($keys[$keyname])) {
$keys[$keyname] = array();
$keyTypes[$keyname] = '';
if (0+(int)@$fx['Non_unique'] == 0) {
$keyTypes[$keyname] = 'UNIQUE';
}
}
$keys[$keyname][$fx['Seq_in_index']] = $fx['Column_name'];
}
foreach ($keys as $kn => $kd) {
if (!isset($indices[$table])) {
$indices[$table] = array();
}
$index = $keyTypes[$kn] .':' . implode(',', $kd);
$struct .= $table . '::' . $kn . ':' . $index . "\r\n";
$indices[$table][$kn] = $index;
}
}
}
if (!isset($tables['global'])) {
$out .= "# Missing `global` table. Has the server installation been completed?\r\n";
return array(100, $out);
}
if (!isset($tables['global']['schema'])) {
$schema = 'none';
} else {
$fglob = selecta('global', 1);
$schema = $fglob['schema'];
}
if ($newSchema) {
$newTables = array();
$newIndices = array();
$lines = explode("\n", $newSchema);
$foundVer = false;
foreach ($lines as $line) {
$line = trim($line);
if ((strlen($line) != 0) &&
(substr($line, 0, 1) != '#')) {
$parts = explode(':', $line);
if (count($parts) >= 3) {
$table = ''.(string)@$parts[0];
if ($table == '') {
if ($parts[1] == 'schema') {
if ($foundVer) {
$out .= "# ERROR: Schema specified twice?\r\n";
return array(101, $out);
}
$newSchema = $parts[2];
$foundVer = true;
} elseif ($parts[1] == 'rename') {
if ($parts[3] == '') {
$renameTables[$parts[2]] = $parts[4];
} else {
$renameContent[$parts[2] . ':' . $parts[3]] = $parts[4];
}
}
} else {
if (!isset($newTables[$table])) {
$newTables[$table] = array();
}
if ($parts[1] == '') {
$keyname = ''.(string)@$parts[2];
$newIndices[$table][$keyname] = $parts[3] . ':' . $parts[4];
} else {
$field = ''.(string)@$parts[1];
$newTables[$table][$field] = $parts[2] . ':' . $parts[3] . ':' . $parts[4] . ':' . $parts[5] . ':' . $parts[6];
}
}
}
//
}
}
$apply = false;
if ($foundVer) {
$out .= '# Operating on database: ' . $dbname . "\r\n";
$out .= '# Existing Schema: ' . $schema . "\r\n";
$out .= '# Into New Schema: ' . $newSchema . "\r\n";
$upgradeError = false;
if ($schema != $newSchema) {
if ($action == 'apply') {
$apply = true;
$out .= "# Applying changes.\r\n";
} else {
$out .= "# This is only a preflight test.\r\n";
}
} else {
if ($action == 'reapply') {
$apply = true;
$out .= "# Re-applying changes in spite of same schema identifier.\r\n";
} else {
$out .= "# Schema is already up-to-date. Checking consistency.\r\n";
}
}
foreach ($renameTables as $kr => $kn) {
if (isset($tables[$kr])) {
if (!isset($tables[$kn])) {
if (strtoupper($kn) != strtoupper($kr)) {
$out .= '# Renaming table ' . $kr . ' to ' . $kn . "\r\n";
$tables[$kn] = $tables[$kr];
$indices[$kn] = $indices[$kr];
$out .= applyChange($apply, 'RENAME TABLE `' . $kr . '` TO `' . $kn . '`');
unset($tables[$kr]);
unset($indices[$k]);
}
} else {
$out .= '# I am supposed to rename table ' . $kr . ' to ' . $kn . ', but ' . $kn . ' already exists!' . "\r\n";
$upgradeError = true;
}
}
}
$createTables = array();
$deleteTables = array();
foreach ($newTables as $tn => $td) {
if (!isset($tables[$tn])) {
$createTables[$tn] = true;
}
}
foreach ($tables as $tn => $td) {
if (!isset($newTables[$tn])) {
$deleteTables[$tn] = true;
$qs = 'SHOW TABLES LIKE "' . $tn . '"';
$found = false;
if ($fs = sqf($qs)) {
$qs = 'SELECT count(TRUE) AS `rows` FROM `' . $tn . '` WHERE TRUE';
try {
$fcount = sqf($qs);
} catch (Exception $e) {
$fcount['rows'] = -1;
}
$rows = 0+(int)@$fcount['rows'];
$out .= '# I am supposed to delete table ' . $tn . ' which has ' . $rows . ' ';
if ($rows == 1) { $out .= 'row'; } else { $out .= 'rows'; }
$out .= ".\r\n";
$out .= applyChange($apply, 'DROP TABLE `' . $tn . '`');
} else {
$out .= '# I am supposed to delete table ' . $tn . ' which does not exist.';
$out .= "\r\n";
}
unset($tables[$tn]);
unset($indices[$tn]);
}
}
foreach ($createTables as $tn => $td) {
if (!isset($tables[$tn])) {
$sq = 'CREATE TABLE `' . $tn . "` (\r\n";
$inds = '';
$first = true;
foreach ($newTables[$tn] as $field => $data) {
$opts = explode(':', $data);
if (!$first) { $sq .= ",\r\n"; }
$first = false;
$sq .= ' `' . $field . '` ';
$sq .= describeColumn($data);
if ($opts[2] == 'PRI') {
$inds .= ",\r\n" . ' PRIMARY KEY (`' . $field . '`)';
}
}
foreach ($newIndices[$tn] as $key => $data) {
if ($key != 'PRIMARY') {
$inds .= ",\r\n" . ' INDEX `' . $key . '` (';
$parts = explode(':', $data);
$fields = explode(',', $parts[1]);
$ff = true;
foreach ($fields as $field) {
if (!$ff) { $inds .= ', '; };
$ff = false;
$inds .= '`' . $field . '`';
}
$inds .= ')';
}
}
$sq .= $inds;
$sq .= "\r\n) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci\r\n";
$out .= applyChange($apply, $sq);
}
}
foreach ($renameContent as $rk => $name) {
$parts = explode(':', $rk);
$table = $parts[0];
$field = $parts[1];
if ($table != '') {
if ($field != '') {
if (isset($tables[$tn][$name])) {
$out .= '# I am supposed to rename column ' . $table . '.' . $field . ' to ' . $name . ' but it alraedy exists.';
$out .= "\r\n";
} else {
$sq = 'ALTER TABLE `' . $table . '` RENAME COLUMN `' . $field . '` TO `' . $name . '`';
$out .= applyChange($apply, $sq);
$tables[$tn][$name] = $tables[$tn][$field];
unset($tables[$tn][$field]);
}
}
}
}
foreach ($newTables as $tn => $td) {
$otd = $tables[$tn];
$position = 'FIRST';
foreach ($td as $field => $opts) {
if (isset($otd[$field])) {
$oopts = $otd[$field];
if ($opts != $oopts) {
$out .= '# Field options for ' . $tn . '.' . $field . ' differ:' . "\r\n";
$out .= '# ' . $oopts . ' => ' . $opts . "\r\n";
}
} else {
$out .= '# Field missing: ' . $tn . '.' . $field . "\r\n";
$sq = 'ALTER TABLE `' . $tn . '` ADD COLUMN `' . $field . '` ';
$sq .= describeColumn($opts);
$sq .= ' ' . $position;
$out .= applyChange($apply, $sq);
}
$position = 'AFTER `' . $field . '`';
}
foreach ($otd as $field => $oopts) {
$found = false;
if (!isset($td[$field])) {
$out .= '# I need to delete ' . $field . ' from ' . $tn . ".\r\n";
$sq = 'ALTER TABLE `' . $tn . '` DROP COLUMN `' . $field . '`';
$out .= applyChange($apply, $sq);
}
}
}
if ($apply && ($newSchema != $schema)) {
try {
update('global', array('id' => array('TRUE')), array('schema' => $newSchema));
} catch (Exception $e) {
$out .= "This database is missing the `schema` field in the `global` table.\r\n";
}
}
} else {
$out .= "Version not specified.\r\n";
return array(102, $out);
}
} else {
$out .= '# Generated by updateDatabase Tool' . "\r\n";
$out .= "\r\n";
$out .= ':database:' . $dbname . "\r\n";
$out .= ':schema:' . $schema . "\r\n";
$out .= $struct;
}
return array(0, $out);
}