-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOgerDbStructMysql.class.php
More file actions
1748 lines (1337 loc) · 55.1 KB
/
OgerDbStructMysql.class.php
File metadata and controls
1748 lines (1337 loc) · 55.1 KB
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
#LICENSE BEGIN
**********************************************************************
* OgerArch - Archaeological Database is released under the GNU General Public License (GPL) <http://www.gnu.org/licenses>
* Copyright (C) Gerhard Öttl <gerhard.oettl@ogersoft.at>
**********************************************************************
#LICENSE END
*/
/**
* Handle database structure for mysql databases.
* @see class OgerDbStruct.<br>
* This class works in a "pseudo-case-insensitive" way.
* Names (tablenames, columnnames, indexnames, ...) are searched
* case insensitive, so it is not possible to have the same name with different
* lettercase twice in the same area. It is no problem to have the same
* name in different areas. Though the names are searched in a case independent way
* they are stored case sensitive and can be used this way if necessary.<br>
* The structure does not contain privileges.<br>
* Collations are handled (which in turn modifies charset).<br>
* Cross database references are NOT handled by design.<br>
* Handling of views is experimental and does NOT work well beetween linux and windows.<br>
*
*/
/* TODO
* - optimize speed
* - read structure at once and not per table.
*/
/* FIXME
* unhandled situations:
* - AUTO_INCREMENT columns needs an index. This is not forced and
* therefore some combinations of add/refresh/cleanup will fail.
* So we have to check/force an index for autoInc columns.
* - addTableColumn -> add column without autoInc, add index, refresh with autoInc
* - refreshTableColumn -> add index, refresh with autoInc
*
* - maybe cleanupTableIndex, refreshTableIndex
* has to check that an index for autoInc columns remain ???
*/
/* MEMO
* - temporary disable constraint checking
* SET foreign_key_checks = 0;
*/
class OgerDbStructMysql extends OgerDbStruct {
const BEFORE_FIRST_COL = -1;
protected $quoteNamBegin = '`';
protected $quoteNamEnd = '`';
private $defCatalogName = "def";
private $sqlServerOs;
private $refDbStruct;
private $curDbStruct;
private $dbToTplMode;
private $initialRefDbStruct;
/**
* @see OgerDbStruct::__construct().
* @throw Throws an exception if the driver name does not fit.
* @globalOpts Use global opts array even if used only at some points. Keys are option names.
*/
public function __construct($conn, $dbName) {
parent::__construct($conn, $dbName);
if ($this->driverName != "mysql") {
throw new Exception("Invalid driver {$this->driverName} for " . __CLASS__);
}
// get platform - needed for case sensitive check.
$pstmt = $this->conn->prepare("SHOW VARIABLES LIKE 'version_compile_os'");
$pstmt->execute();
$records = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
$this->sqlServerOs = $records[0];
} // eo constructor
/**
* Get the current database structure.
* @see OgerDbStruct::getDbStruct().
*/
public function getDbStruct() {
// in db-to-template mode return the initial reference structure
if ($this->dbToTplMode) {
$this->log(static::LOG_NOTICE, "-- Get db struct in db-to-template mode: Return initial reference structure.\n");
return ($this->initialRefDbStruct);
}
$this->log(static::LOG_NOTICE, "-- Read current database structure.\n");
// get structure head
$struct = $this->getNewStructHead();
$struct["DBSTRUCT_META"]["HOSTNAME"] = gethostname();
// TODO ip-number of database connection
// get schema structure
$pstmt = $this->conn->prepare("
SELECT SCHEMA_NAME,DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE CATALOG_NAME=:catalogName AND
SCHEMA_NAME=:dbName
");
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName));
$schemaRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
if (count($schemaRecords) > 1) {
throw new Exception("More than one schema found for database name {$this->dbName}.");
}
if (count($schemaRecords) < 1) {
throw new Exception("No schema found for database name {$this->dbName}.");
}
$struct["SCHEMA_META"] = $schemaRecords[0];
$pstmt = $this->conn->prepare("SHOW VARIABLES LIKE '%case%'");
$pstmt->execute();
$schemaRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$schemaRecords as $schemaRecord) {
$struct["SCHEMA_META"][$schemaRecord["Variable_name"]] = $schemaRecord["Value"];
}
$pstmt = $this->conn->prepare("SHOW VARIABLES LIKE '%compile%'");
$pstmt->execute();
$schemaRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$schemaRecords as $schemaRecord) {
$struct["SCHEMA_META"][$schemaRecord["Variable_name"]] = $schemaRecord["Value"];
}
$pstmt = $this->conn->prepare("SHOW VARIABLES LIKE '%version%'");
$pstmt->execute();
$schemaRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$schemaRecords as $schemaRecord) {
$struct["SCHEMA_META"][$schemaRecord["Variable_name"]] = $schemaRecord["Value"];
}
// get table structure
$stmt = "
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG=:catalogName AND
TABLE_SCHEMA=:dbName AND TABLE_TYPE='BASE TABLE'
";
if ($this->getParam("whereTables")) {
$stmt .= " AND {$this->getParam("whereTables")}";
}
$pstmt = $this->conn->prepare($stmt);
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName));
$tableRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
$tableNames = array();
foreach ((array)$tableRecords as $tableRecord) {
$tableName = $tableRecord["TABLE_NAME"];
$tableKey = strtolower($tableName);
$struct["TABLES"][$tableKey] = $this->getTableStruct($tableName);
} // eo table loop
// get views
$stmt = "
SELECT TABLE_NAME, VIEW_DEFINITION,
CHECK_OPTION, IS_UPDATABLE,
CHARACTER_SET_CLIENT, COLLATION_CONNECTION
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_CATALOG=:catalogName AND
TABLE_SCHEMA=:dbName
";
$pstmt = $this->conn->prepare($stmt);
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName));
$viewRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
$viewNames = array();
foreach ((array)$viewRecords as $viewRecord) {
$viewName = $viewRecord["TABLE_NAME"];
$viewKey = strtolower($viewName);
$struct["VIEWS"][$viewKey] = $this->getViewStruct($viewRecord);
} // eo view loop
return $struct;
} // eo get db struct
/**
* Get the database structure for one table.
* @param $tableName Name of the table for which we want to get the structure.
* @return Array with table structure.
*/
public function getTableStruct($tableName) {
$struct = array();
$pstmt = $this->conn->prepare("
SELECT TABLE_NAME, ENGINE, TABLE_COLLATION
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG=:catalogName AND
TABLE_SCHEMA=:dbName AND
TABLES.TABLE_NAME=:tableName
");
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName, "tableName" => $tableName));
$tableRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
if (count($tableRecords) > 1) {
throw new Exception("More than one table schema found for table name {$tableName}.");
}
if (count($tableRecords) < 1) {
throw new Exception("No table schema found for table name {$tableName}.");
}
$tableRecord = reset($tableRecords);
$tableKey = strtolower($tableName);
$struct["TABLE_META"] = $tableRecord;
// -------------------
// get columns info
// COLUMN_KEY is short index info (PRI, MUL, ...)
// most important is COLUMN_TYPE - e.g. int(11)
$pstmt = $this->conn->prepare("
SELECT TABLE_NAME, COLUMN_NAME,
COLUMN_TYPE, DATA_TYPE,
COLUMN_DEFAULT, IS_NULLABLE,
CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, CHARACTER_SET_NAME, COLLATION_NAME,
NUMERIC_PRECISION, NUMERIC_SCALE,
COLUMN_KEY, EXTRA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG=:catalogName AND
TABLE_SCHEMA=:dbName AND
TABLE_NAME=:tableName
ORDER BY ORDINAL_POSITION
");
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName, "tableName" => $tableName));
$columnRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$columnRecords as $columnRecord) {
$columnName = $columnRecord["COLUMN_NAME"];
$columnKey = strtolower($columnName);
// if column is not nullable but default value is NULL then
// unset the default value and let the database decide what to do
if ($columnRecord["COLUMN_DEFAULT"] === null && $columnRecord["IS_NULLABLE"] == "NO") {
unset($columnRecord["COLUMN_DEFAULT"]);
}
// unset some "unused" fields
if (!$columnRecord["EXTRA"]) {
unset($columnRecord["EXTRA"]);
}
if (!$columnRecord["COLUMN_KEY"]) {
unset($columnRecord["COLUMN_KEY"]);
}
if ($columnRecord["CHARACTER_MAXIMUM_LENGTH"] === null) {
unset($columnRecord["CHARACTER_MAXIMUM_LENGTH"]);
}
if ($columnRecord["CHARACTER_OCTET_LENGTH"] === null) {
unset($columnRecord["CHARACTER_OCTET_LENGTH"]);
}
if ($columnRecord["CHARACTER_SET_NAME"] === null) {
unset($columnRecord["CHARACTER_SET_NAME"]);
}
if ($columnRecord["COLLATION_NAME"] === null) {
unset($columnRecord["COLLATION_NAME"]);
}
if ($columnRecord["NUMERIC_PRECISION"] === null) {
unset($columnRecord["NUMERIC_PRECISION"]);
}
if ($columnRecord["NUMERIC_SCALE"] === null) {
unset($columnRecord["NUMERIC_SCALE"]);
}
$struct["COLUMNS"][$columnKey] = $columnRecord;
} // eo column loop
// ---------------
// get key info
// correstponding table name is STATISTICS !
$pstmt = $this->conn->prepare("
SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_CATALOG=:catalogName AND
TABLE_SCHEMA=:dbName AND
TABLE_NAME=:tableName
ORDER BY INDEX_NAME, SEQ_IN_INDEX
");
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName, "tableName" => $tableName));
$indexRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$indexRecords as $indexRecord) {
$indexName = $indexRecord["INDEX_NAME"];
$indexKey = strtolower($indexName);
$indexRecord["UNIQUE"] = ($indexRecord["NON_UNIQUE"] ? "0" : "1");
// detect index type
$indexType = "";
if ($indexName == "PRIMARY") {
$indexType = "PRIMARY";
}
elseif (!$indexRecord["NON_UNIQUE"]) {
$indexType = "UNIQUE";
}
// the meta info is taken from the last column info which overwrites the prevous meta info
$struct["INDICES"][$indexKey]["INDEX_META"]["INDEX_NAME"] = $indexName;
$struct["INDICES"][$indexKey]["INDEX_META"]["INDEX_KEY_TYPE"] = $indexType;
$struct["INDICES"][$indexKey]["INDEX_META"]["TABLE_NAME"] = $indexRecord["TABLE_NAME"];
// index columns
$indexColumnKey = strtolower($indexRecord["COLUMN_NAME"]);
$struct["INDICES"][$indexKey]["INDEX_COLUMNS"][$indexColumnKey] = $indexRecord;
} // eo index loop
// ---------------
// get foreign keys references and columns
/* see <http://stackoverflow.com/questions/953035/multiple-column-foreign-key-in-mysql>
* CREATE TABLE MyReferencingTable AS (
[COLUMN DEFINITIONS]
refcol1 INT NOT NULL,
rofcol2 INT NOT NULL,
CONSTRAINT fk_mrt_ot FOREIGN KEY (refcol1, refcol2)
REFERENCES OtherTable(col1, col2)
) ENGINE=InnoDB;
MySQL requires foreign keys to be indexed, hence the index on the referencing columns
Use of the constraint syntax enables you to name a constraint, making it easier to alter and drop at a later time if needed.
InnoDB enforces foreign keys, MyISAM does not. (The syntax is parsed but ignored)
*/
/*
* ALTER TABLE `testtab4` ADD FOREIGN KEY ( `id1` ) REFERENCES `test`.`testtab1` (
`id1`
) ON DELETE RESTRICT ON UPDATE RESTRICT ;
*/
// the table TABLE_CONSTRAINTS contains only constraint names,
// so we use table KEY_COLUMN_USAGE this time
// we do not support cross database settings, so we removed TABLE_SCHEMA and REFERENCED_TABLE_SCHEMA from query
$pstmt = $this->conn->prepare("
SELECT TABLE_NAME, CONSTRAINT_NAME, COLUMN_NAME, POSITION_IN_UNIQUE_CONSTRAINT,
REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_CATALOG=:catalogName AND
TABLE_SCHEMA=:dbName AND
TABLE_NAME=:tableName AND
REFERENCED_TABLE_NAME IS NOT NULL
ORDER BY CONSTRAINT_NAME, ORDINAL_POSITION
");
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName, "tableName" => $tableName));
$fkRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$fkRecords as $fkRecord) {
$fkName = $fkRecord["CONSTRAINT_NAME"];
$fkKey = strtolower($fkName);
// the meta info is taken from the last entry info which overwrites the prevous meta info
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["FOREIGN_KEY_NAME"] = $fkName;
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["TABLE_NAME"] = $fkRecord["TABLE_NAME"];
//$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["REFERENCED_TABLE_SCHEMA"] = $fkRecord["REFERENCED_TABLE_SCHEMA"];
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["REFERENCED_TABLE_NAME"] = $fkRecord["REFERENCED_TABLE_NAME"];
// referenced columns
$fkColumnKey = strtolower($fkRecord["COLUMN_NAME"]);
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_COLUMNS"][$fkColumnKey] = $fkRecord;
} // eo foreign key columns loop
// ---------------
// get foreign keys constraint rules
// unused columns: UNIQUE_CONSTRAINT_CATALOG, UNIQUE_CONSTRAINT_SCHEMA, UNIQUE_CONSTRAINT_NAME
$pstmt = $this->conn->prepare("
SELECT CONSTRAINT_SCHEMA, TABLE_NAME, CONSTRAINT_NAME,
MATCH_OPTION, UPDATE_RULE, DELETE_RULE, REFERENCED_TABLE_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_CATALOG=:catalogName AND
CONSTRAINT_SCHEMA=:dbName AND
TABLE_NAME=:tableName
ORDER BY TABLE_NAME, CONSTRAINT_NAME
");
$pstmt->execute(array("catalogName" => $this->defCatalogName, "dbName" => $this->dbName, "tableName" => $tableName));
$fkRulesRecords = $pstmt->fetchAll(PDO::FETCH_ASSOC);
$pstmt->closeCursor();
foreach ((array)$fkRulesRecords as $fkRulesRecord) {
$fkName = $fkRulesRecord["CONSTRAINT_NAME"];
$fkKey = strtolower($fkName);
// complete the meta info
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["MATCH_OPTION"] = $fkRulesRecord["MATCH_OPTION"];
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["UPDATE_RULE"] = $fkRulesRecord["UPDATE_RULE"];
$struct["FOREIGN_KEYS"][$fkKey]["FOREIGN_KEY_META"]["DELETE_RULE"] = $fkRulesRecord["DELETE_RULE"];
} // eo foreign key columns loop
return $struct;
} // eo get table struc
/**
* Prepare structure for one view.
* @param $viewRecord Record with view data.
* @return Array with view structure.
*/
public function getViewStruct($viewRecord) {
$struct = array();
// extract definition
$definition = $viewRecord['VIEW_DEFINITION'];
unset($viewRecord['VIEW_DEFINITION']);
// remove schema name to make transferable
$schemaQ = $this->quoteName($this->dbName);
$definition = preg_replace("/{$schemaQ}\./", "", $definition);
// put all remaining into meta data
$struct["VIEW_META"] = $viewRecord;
$struct['DEFINITION'] = $definition;
return $struct;
} // eo get view struc
// ##############################################
// DRIVER SPECIFIC HELPERS
// ##############################################
/**
* Precheck before process changes.
* @param $refDbStruct Array with the reference database structure.
* @param $curDbStruct Optional array with the current database structure.
* If not present it is located from the database connection.
*/
private function preProcessCheck($refDbStruct = null, $curDbStruct = null) {
// do not set database reference structure in db-to-template mode
// this is done by startDbToTplMode and must not be changed later.
if ($refDbStruct && !$this->dbToTplMode) {
$this->refDbStruct = $refDbStruct;
}
if (!$this->refDbStruct) {
throw new Exception ("Reference database structure required.");
}
$driverName = $this->refDbStruct["DBSTRUCT_META"]["DRIVER_NAME"];
if ($driverName != "mysql") {
throw new Exception ("Driver '$driverName' not compatible. Only driver 'mysql' supported.");
}
// read current database structure if not present
if (!$this->curDbStruct) {
$this->curDbStruct = $this->getDbStruct();
}
// do not overwrite case sensitive database systems with lowercase converted reference structures
// lower_case_table_names: 0=linux, 1=windows, 2=mac
// TODO provide forceLowerCase or ignoreLowerCase option ???
if ($this->curDbStruct["SCHEMA_META"]["lower_case_table_names"] != 1 &&
$this->refDbStruct["SCHEMA_META"]["lower_case_table_names"] == 1) {
throw new Exception ("It is not allowed to apply lower case forced (table) reference structures" .
" to a case sensitive database system.");
}
} // eo prechecks
/**
* Handle table name lettercase changes.
* @param $refTableStruct Array with the reference table structure.
* @return True if the table was renamed because of lettercase change, false otherwise.
*/
private function handleTableCase($refTableStruct) {
$this->preProcessCheck();
$refTableName = $refTableStruct["TABLE_META"]["TABLE_NAME"];
$tableKey = strtolower($refTableName);
$curTableName = $this->curDbStruct["TABLES"][$tableKey]["TABLE_META"]["TABLE_NAME"];
// if current table does not exist nothing can be renamed
if (!$curTableName) {
return false;
}
// check that table name only differ in lettercase
if (strtolower($refTableName) != strtolower($curTableName)) {
return false;
}
// difference in lettercase is only of interest on case sensitive systems
if ($refTableName != $curTableName &&
$this->curDbStruct["SCHEMA_META"]["lower_case_table_names"] != 1) {
$refTableNameQ = $this->quoteName($refTableName);
$curTableNameQ = $this->quoteName($curTableName);
$stmt = "RENAME TABLE {$curTableNameQ} TO {$refTableNameQ}";
$this->execChange($stmt);
// adapt lettercase on the fly
array_walk_recursive($this->curDbStruct["TABLES"][$tableKey], "OgerDbStructMysql::walkTableCase", $refTableName);
return true;
} // eo rename lettercase
return false;
} // eo table name lettercase handling
/**
* Adopt current table structure array on the fly after table case change.
*/
public static function walkTableCase(&$oldValue, $key, $newValue) {
// sanity check to restrict change to matching table names
if ($key == "TABLE_NAME" &&
strtolower($oldValue) == strtolower($newValue)) {
$oldValue = $newValue;
}
} // eo adopt table case in structure
/**
* Handle view name lettercase changes.
* @param $refViewStruct Array with the reference view structure.
* @return True if the view was renamed because of lettercase change, false otherwise.
*/
private function handleViewCase($refViewStruct) {
$this->preProcessCheck();
$refViewName = $refViewStruct["VIEW_META"]["TABLE_NAME"];
$viewKey = strtolower($refViewName);
$curViewName = $this->curDbStruct["VIEW"][$viewKey]["VIEW_META"]["TABLE_NAME"];
// if current view does not exist nothing can be renamed
if (!$curViewName) {
return false;
}
// check that view name only differ in lettercase
if (strtolower($refViewName) != strtolower($curViewName)) {
return false;
}
// difference in lettercase is only of interest on case sensitive systems
if ($refViewName != $curViewName &&
$this->curDbStruct["SCHEMA_META"]["lower_case_table_names"] != 1) {
$refViewNameQ = $this->quoteName($refViewName);
$curViewNameQ = $this->quoteName($curViewName);
$stmt = "RENAME TABLE {$curViewNameQ} TO {$refViewNameQ}";
$this->execChange($stmt);
// adapt lettercase on the fly
array_walk_recursive($this->curDbStruct["VIEW"][$viewKey], "OgerDbStructMysql::walkTableCase", $refViewName);
return true;
} // eo rename lettercase
return false;
} // eo view name lettercase handling
// ##############################################
// ADD STRUCTURE
// ##############################################
/**
* Add missing tables, columns, indices or foreign keys to the database.
* @see OgerDbStruct::addDbStruct().
*/
public function addDbStruct($refDbStruct = null) {
$this->preProcessCheck($refDbStruct);
// table loop
foreach ((array)$this->refDbStruct["TABLES"] as $refTableKey => $refTableStruct) {
$refTableName = $refTableStruct["TABLE_META"]["TABLE_NAME"];
$curTableStruct = $this->curDbStruct["TABLES"][$refTableKey];
if (!$curTableStruct) {
$this->addTableCore($refTableStruct);
}
else {
$this->addTableColumns($refTableStruct);
$this->addTableIndices($refTableStruct);
}
} // eo table loop
// add foreign keys after all tables, columns and indices has been created
foreach ((array)$this->refDbStruct["TABLES"] as $refTableKey => $refTableStruct) {
$this->addTableForeignKeys($refTableStruct);
} // eo include foreign keys
// view loop
foreach ((array)$this->refDbStruct["VIEWS"] as $refViewKey => $refViewStruct) {
$curViewStruct = $this->curDbStruct["VIEWS"][$refViewKey];
if (!$curViewStruct) {
$this->addView($refViewStruct);
}
} // eo view loop
} // eo add db struc
/**
* Add a table to the current database structure.
* @param $tableStruct Array with the table structure.
*/
public function addTable($tableStruct) {
$this->preProcessCheck();
$this->addTableCore($tableStruct); // includes columns
//$this->addTableIndices($tableStruct);
//$this->addTableForeignKeys($tableStruct);
} // eo add table
/**
* Add table (with columns, but without indexes
* and without foreign keys) to the current database structure.
* @param $tableStruct Array with the table structure.
*/
public function addTableCore($tableStruct) {
$this->preProcessCheck();
$tableMeta = $tableStruct["TABLE_META"];
$tableName = $tableMeta["TABLE_NAME"];
$tableNameQ = $this->quoteName($tableName);
$stmt = "CREATE TABLE $tableNameQ (\n ";
$delim = "";
foreach ((array)$tableStruct["COLUMNS"] as $columnStruct) {
$stmt .= $delim . $this->columnDefStmt($columnStruct);
$delim = ",\n ";
} // eo column loop
// add indices here, because auto increment columns need one
foreach ((array)$tableStruct["INDICES"] as $indexKey => $indexStruct) {
$stmt .= $delim . $this->indexDefStmt($indexStruct);
} // eo index loop
$stmt .= "\n)";
// table defaults
// Note on charset:
// Looks like mysql derives the charset from the collation
// via the INFORMATION_SCHEMA.COLLATION_CHARACTER_SET_APPLICABILITY table
// and does this internally automatically if a collation is given.
// So we depend on this - provide the collation and omit the charset.
$stmt .= " ENGINE={$tableMeta['ENGINE']}" .
($this->getParam("ignoreCollate") ? "" : " DEFAULT COLLATE={$tableMeta['TABLE_COLLATION']}") .
// " CHARSET={$tableMeta['']}" . // see note above
"";
// execute the statement
$this->execChange($stmt);
// update current db struct array
//unset($tableStruct["INDICES"]);
unset($tableStruct["FOREIGN_KEYS"]);
$this->curDbStruct["TABLES"][strtolower($tableName)] = $tableStruct;
} // eo add table
/**
* Add missing columns to a table.
* @param $refTableStruct Array with the reference table structure.
*/
public function addTableColumns($refTableStruct = null) {
$this->preProcessCheck();
// rename lettercase
$this->handleTableCase($refTableStruct);
$curTableStruct = $this->curDbStruct["TABLES"][strtolower($refTableStruct["TABLE_META"]["TABLE_NAME"])];
$afterColumnName = static::BEFORE_FIRST_COL;
foreach ((array)$refTableStruct["COLUMNS"] as $refColumnKey => $refColumnStruct) {
if (!$curTableStruct["COLUMNS"][$refColumnKey]) {
$this->addTableColumn($refColumnStruct, $afterColumnName);
}
// this column exists (old or new created) so the next missing column will be added after this
$afterColumnName = $refColumnStruct["COLUMN_NAME"];
} // eo column loop
} // eo add missing columns
/**
* Add missing indices.
* @param $refTableStruct Array with the reference table structure.
*/
public function addTableIndices($refTableStruct = null) {
$this->preProcessCheck();
// rename lettercase
$this->handleTableCase($refTableStruct);
$curTableStruct = $this->curDbStruct["TABLES"][strtolower($refTableStruct["TABLE_META"]["TABLE_NAME"])];
foreach ((array)$refTableStruct["INDICES"] as $refIndexKey => $refIndexStruct) {
if (!$curTableStruct["INDICES"][$refIndexKey]) {
$this->addTableIndex($refIndexStruct);
}
}
} // eo add missing indices
/**
* Add missing foreign keys.
* @param $refTableStruct Array with the reference table structure.
*/
public function addTableForeignKeys($refTableStruct = null) {
$this->preProcessCheck();
// rename lettercase
$this->handleTableCase($refTableStruct);
$curTableStruct = $this->curDbStruct["TABLES"][strtolower($refTableStruct["TABLE_META"]["TABLE_NAME"])];
foreach ((array)$refTableStruct["FOREIGN_KEYS"] as $refFkKey => $refFkStruct) {
if (!$curTableStruct["FOREIGN_KEYS"][$refFkKey]) {
$this->addTableForeignKey($refFkStruct);
}
}
} // eo add missing foreign keys
/**
* Add a column to a table structure.
* @param $columnStruct Array with the table structure.
* @param $afterColumnName: Passed to columnDefStmt(). Description see there.
*/
public function addTableColumn($columnStruct, $afterColumnName) {
$this->preProcessCheck();
$tableName = $columnStruct["TABLE_NAME"];
$stmt = "ALTER TABLE " . $this->quoteName($tableName) .
" ADD COLUMN " . $this->columnDefStmt($columnStruct, $afterColumnName);
$this->execChange($stmt);
// update current db struct array
$tableKey = strtolower($tableName);
$colKey = strtolower($columnStruct["COLUMN_NAME"]);
// append after last existing column by default
$afterColPos = count($this->curDbStruct["TABLES"][$tableKey]["COLUMNS"]);
if ($afterColumnName) {
if ($afterColumnName == static::BEFORE_FIRST_COL) {
$afterColPos = 0; // ordinal pos starts at 1
}
else {
$afterColPos = 0; // ordinal pos starts at 1
foreach ($this->curDbStruct["TABLES"][$tableKey]["COLUMNS"] as $tmpColKey => $tmpCol) {
$afterColPos++;
if ($tmpColKey == strtolower($afterColumnName)) {
break;
}
}
}
}
// insert new column info at correct position into column struct array
$this->curDbStruct["TABLES"][$tableKey]["COLUMNS"] =
array_slice($this->curDbStruct["TABLES"][$tableKey]["COLUMNS"], 0, $afterColPos, true) +
array($colKey => $columnStruct) +
array_slice($this->curDbStruct["TABLES"][$tableKey]["COLUMNS"], $afterColPos, NULL, true);
} // eo add column to table
/**
* Add an index to a table.
* @param $indexStruct Array with the index structure.
*/
public function addTableIndex($indexStruct) {
$this->preProcessCheck();
$tableName = $indexStruct["INDEX_META"]["TABLE_NAME"];
$tableNameQ = $this->quoteName($tableName);
$stmt = "ALTER TABLE $tableNameQ ADD " . $this->indexDefStmt($indexStruct);
$this->execChange($stmt);
// update current db struct array
$indexKey = strtolower($indexStruct["INDEX_META"]["INDEX_NAME"]);
$this->curDbStruct["TABLES"][strtolower($tableName)][$indexKey] = $indexStruct;
} // eo add index
/**
* Add a foreign key to a table.
* @param $fkStruct Array with the foreign key structure.
*/
public function addTableForeignKey($fkStruct) {
$this->preProcessCheck();
$tableName = $fkStruct["FOREIGN_KEY_META"]["TABLE_NAME"];
$tableNameQ = $this->quoteName($tableName);
$stmt = "ALTER TABLE $tableName ADD " . $this->foreignKeyDefStmt($fkStruct);
$this->execChange($stmt);
// update current db struct array
$fkKey = strtolower($fkStruct["FOREIGN_KEY_META"]["FOREIGN_KEY_NAME"]);
$this->curDbStruct["TABLES"][strtolower($tableName)][$fkKey] = $fkStruct;
} // eo add foreign key
/**
* Add a view to the current database structure.
* @param $viewStruct Array with the view structure.
*/
public function addView($viewStruct) {
$this->preProcessCheck();
$viewMeta = $viewStruct["VIEW_META"];
$viewName = $viewMeta["TABLE_NAME"];
$viewNameQ = $this->quoteName($viewName);
$stmt = "CREATE VIEW $viewNameQ AS {$viewStruct['DEFINITION']}";
$this->execChange($stmt);
$this->curDbStruct["VIEWS"][strtolower($viewName)] = $viewStruct;
} // eo add view
// ##############################################
// REFRESH STRUCTURE
// ##############################################
/**
* Refresh existing tables, columns, indices and foreign keys.
* @see OgerDbStruct::refreshDbStruct().
*/
public function refreshDbStruct($refDbStruct = null) {
$this->preProcessCheck($refDbStruct);
// refresh current table if exits
foreach ((array)$this->refDbStruct["TABLES"] as $refTableKey => $refTableStruct) {
$curTableStruct = $this->curDbStruct["TABLES"][$refTableKey];
if ($curTableStruct) {
$this->refreshTableCore($refTableStruct);
$this->refreshTableColumns($refTableStruct);
$this->refreshTableIndices($refTableStruct);
}
} // eo table loop
// refresh foreign keys after all tables, columns and indices has been refreshed
foreach ((array)$this->refDbStruct["TABLES"] as $refTableKey => $refTableStruct) {
$curTableStruct = $this->curDbStruct["TABLES"][$refTableKey];
if ($curTableStruct) {
$this->refreshTableForeignKeys($refTableStruct);
}
} // eo refresh foreign keys
// view loop
foreach ((array)$this->refDbStruct["VIEWS"] as $refViewKey => $refViewStruct) {
$curViewStruct = $this->curDbStruct["VIEWS"][$refViewKey];
if ($curViewStruct) {
$this->refreshView($refViewStruct);
}
} // eo view loop
} // eo refresh struc
/**
* Refresh an existing table.
* @param $refTableStruct Array with the reference table structure.
*/
public function refreshTable($refTableStruct) {
$this->preProcessCheck();
// rename lettercase
$this->handleTableCase($refTableStruct);
$curTableStruct = $this->curDbStruct["TABLES"][strtolower($refTableStruct["TABLE_META"]["TABLE_NAME"])];
$this->refreshTableCore($refTableStruct);
$this->refreshTableColumns($refTableStruct);
$this->refreshTableIndices($refTableStruct);
$this->refreshTableForeignKeys($refTableStruct);
} // eo refresh table
/**
* Refresh an existing table. Meta info and defaults.
* @param $refTableStruct Array with the reference table structure.
*/
public function refreshTableCore($refTableStruct = null) {
$this->preProcessCheck();
// rename lettercase
$this->handleTableCase($refTableStruct);
$tableName = $refTableStruct["TABLE_META"]["TABLE_NAME"];
$curTableStruct = $this->curDbStruct["TABLES"][strtolower($tableName)];
$refTableMeta = $refTableStruct["TABLE_META"];
$curTableMeta = $curTableStruct["TABLE_META"];
$stmt = "";
if ($refTableMeta["ENGINE"] != $curTableMeta["ENGINE"]) {
"ENGINE=" . $refTableMeta["ENGINE"];
}
if (($refTableMeta["TABLE_COLLATION"] != $curTableMeta["TABLE_COLLATION"]) && !$this->getParam("ignoreCollate")) {
$stmt .= " DEFAULT COLLATE=" . $refTableMeta["TABLE_COLLATION"];
}
if ($stmt) {
$stmt .= "ALTER TABLE " . $stmt;
$this->execChange($stmt);
// update current db struct array
$this->curDbStruct["TABLES"][strtolower($tableName)]["TABLE_META"] = $refTableMeta;
}
} // eo refresh table core
/**
* Refresh columns of an existing table.
* @param $refTableStruct Array with the reference table structure.
*/
public function refreshTableColumns($refTableStruct = null) {
$this->preProcessCheck();
// rename lettercase
$this->handleTableCase($refTableStruct);
$tableName = $refTableStruct["TABLE_META"]["TABLE_NAME"];
$curTableStruct = $this->curDbStruct["TABLES"][strtolower($tableName)];
foreach ((array)$refTableStruct["COLUMNS"] as $refColumnKey => $refColumnStruct) {
if ($curTableStruct["COLUMNS"][$refColumnKey]) {