3 * our standard code relies on links.ini files for the relationships in mysql.
5 * as we use 'loose' relationships - eg. we allow '0' as a missing link mysql FORIEGN KEYS do not really work.
7 * There are a couple of ideas behind this code.
9 * a) put the relationships in the table comments FK(col=table:col,col=table:col)
10 * -- we can not put it in the column comments as there is no clean way to update column comments.
11 * -- This can be used by external programs to extract the Relationships.
13 * b) generate triggers? to protect against updates to the database..
15 * -- stored procedures are named
16 * {tablename}_before_{insert|delete|update}
19 * initial code will auto generate triggers
20 * -- how to add User defined modifications to triggers?
21 * -- we can CALL a stored procedure..?
22 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
23 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
24 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
27 * ------- Importing with triggers disabled.
29 * SET @DISABLE_TRIGGER=1; (or anything you like except NULL)
31 * SET @DISABLE_TRIGGER=NULL;
33 * ------ Call a method disabling a particular set of triggers
34 * SET @DISABLE_TRIGGER_the_table_name=1; (or anything you like except NULL)
36 * SET @DISABLE_TRIGGER_the_table_name=NULL;*
39 class Pman_Core_UpdateDatabase_MysqlLinks {
45 function __construct()
48 $this->loadIniFiles();
49 $this->updateTableComments();
51 $this->updateCharacterSet();
53 $ff = HTML_FlexyFramework::get();
54 if (!empty($ff->Pman['enable_trigger_tests'])) {
56 // note we may want to override some of these... - to do special triggers..
57 // as you can only have one trigger per table for each action.
59 $this->createDeleteTriggers();
60 $this->createInsertTriggers();
61 $this->createUpdateTriggers();
67 function loadIniFiles()
69 // will create the combined ini cache file for the running user.
71 $ff = HTML_FlexyFramework::get();
72 $ff->generateDataobjectsCache(true);
73 $this->dburl = parse_url($ff->database);
75 $dbini = 'ini_'. basename($this->dburl['path']);
78 $iniCache = $ff->DB_DataObject[$dbini];
80 $this->schema = parse_ini_file($iniCache, true);
81 $this->links = parse_ini_file(preg_replace('/\.ini$/', '.links.ini', $iniCache), true);
86 function updateTableComments()
88 foreach($this->links as $tbl =>$map) {
89 $this->updateTableComment($tbl, $map);
96 function updateTableComment($tbl, $map)
100 if (!isset($this->schema[$tbl])) {
101 echo "Skip $tbl = table does not exist in schema\n";
106 $q = DB_DAtaObject::factory('core_enum');
110 information_schema.TABLES
112 TABLE_SCHEMA = '{$q->escape($q->database())}'
114 TABLE_NAME = '{$q->escape($tbl)}'
117 $tc = $q->TABLE_COMMENT;
118 //echo "$tbl: $tc\n\n";
119 if (!empty($q->TABLE_COMMENT)) {
121 $tc = trim(preg_replace('/FK\([^)]+\)/', '' , $q->TABLE_COMMENT));
122 //var_dump($tc);exit;
123 // strip out the old FC(....)
127 foreach($map as $k=>$v) {
130 $fkstr = $tc . ' FK(' . implode("\n", $fks) .')';
131 if ($q->TABLE_COMMENT == $fkstr) {
135 $q = DB_DAtaObject::factory('core_enum');
136 $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
142 function createDeleteTriggers()
145 // this should only be enabled if the project settings are configured..
149 // delete triggers on targets -
150 // if you delete a company, and a person points to it, then it should fire an error...
155 // create a list of source/targets from $this->links
159 foreach($this->links as $tbl => $map) {
160 if (!isset($this->schema[$tbl])) {
163 foreach($map as $k =>$v) {
164 list ($tname, $tcol) = explode(':', $v);
167 if (!isset($revmap[$tname])) {
168 $revmap[$tname] = array();
170 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
177 foreach($revmap as $target_table => $sources) {
180 // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
182 if (!isset($this->schema[$target_table])) {
183 echo "Skip $target_table = table does not exist in schema\n";
189 $q = DB_DataObject::factory('core_enum');
191 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
196 CREATE TRIGGER `{$target_table}_before_delete`
197 BEFORE DELETE ON `{$target_table}`
201 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN
204 foreach($sources as $source=>$target) {
205 list($source_table , $source_col) = explode(':', $source);
206 list($target_table , $target_col) = explode(':', $target);
207 $err = substr("Failed Delete {$target_table} refs {$source_table}:{$source_col}", 0, 64);
210 IF OLD.{$target_col} > 0 THEN
211 SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
213 UPDATE `$err` SET x = 1;
219 $ar = $this->listTriggerFunctions($tbl, 'delete');
220 foreach($ar as $fn=>$col) {
222 CALL $fn( OLD.{$col});
232 //DB_DAtaObject::debugLevel(1);
233 $q = DB_DataObject::factory('core_enum');
235 echo "CREATED TRIGGER {$target_table}_before_delete\n";
239 // inserting - row should not point to a reference that does not exist...
245 function createInsertTriggers()
247 foreach($this->links as $tbl => $map) {
248 if (!isset($this->schema[$tbl])) {
252 $q = DB_DataObject::factory('core_enum');
254 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
259 CREATE TRIGGER `{$tbl}_before_insert`
260 BEFORE INSERT ON `{$tbl}`
264 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN
267 foreach($map as $source_col=>$target) {
268 // check that source_col exists in schema.
269 if (!isset($this->schema[$tbl][$source_col])) {
275 list($target_table , $target_col) = explode(':', $target);
277 if (!isset($this->schema[$target_table])) {
278 // skip... target table does not exist
283 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
286 if NEW.{$source_col} > 0 THEN
287 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
289 UPDATE `$err` SET x = 1;
298 $ar = $this->listTriggerFunctions($tbl, 'insert');
299 foreach($ar as $fn=>$col) {
301 CALL $fn( NEW.{$col});
310 //echo $trigger; exit;
311 //DB_DAtaObject::debugLevel(1);
312 $q = DB_DataObject::factory('core_enum');
314 echo "CREATED TRIGGER {$tbl}_before_insert\n";
327 function createUpdateTriggers()
329 foreach($this->links as $tbl => $map) {
330 if (!isset($this->schema[$tbl])) {
334 $q = DB_DataObject::factory('core_enum');
336 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
341 CREATE TRIGGER `{$tbl}_before_update`
342 BEFORE UPDATE ON `{$tbl}`
346 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN
349 foreach($map as $source_col=>$target) {
350 // check that source_col exists in schema.
351 if (!isset($this->schema[$tbl][$source_col])) {
357 list($target_table , $target_col) = explode(':', $target);
359 if (!isset($this->schema[$target_table])) {
360 // skip... target table does not exist
364 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
367 if NEW.{$source_col} > 0 THEN
368 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
370 UPDATE `$err` SET x = 1;
376 $ar = $this->listTriggerFunctions($tbl, 'update');
377 foreach($ar as $fn=>$col) {
379 CALL $fn(OLD.{$col}, NEW.{$col});
388 //echo $trigger; exit;
389 //DB_DAtaObject::debugLevel(1);
390 $q = DB_DataObject::factory('core_enum');
392 echo "CREATED TRIGGER {$tbl}_before_update\n";
406 * check the information schema for any methods that match the trigger criteria.
407 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
408 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
409 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
413 // type = update/insert/delete
415 function listTriggerFunctions($table, $type)
417 static $cache = array();
418 if (!isset($cache[$table])) {
419 $cache[$table] = array();
420 $q = DB_DAtaObject::factory('core_enum');
424 information_schema.ROUTINES
426 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
428 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
430 ROUTINE_TYPE = 'PROCEDURE'
433 while ($q->fetch()) {
434 $cache[$table][] = $q->SPECIFIC_NAME;
438 // now see which of the procedures match the specification..
440 foreach($cache[$table] as $cname) {
441 $bits = explode("_before_{$type}_", $cname);
442 if (count($bits) < 2) {
445 $ret[$cname] = $bits[1];
450 function updateCharacterSet()
452 foreach (array_keys($this->schema) as $tbl){
454 if(strpos($tbl, '__keys') !== false ){
458 $ce = DB_DataObject::factory('core_enum');
462 CCSA.character_set_name csname,
463 CCSA.collation_name collatename
465 information_schema.`TABLES` T,
466 information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
468 CCSA.collation_name = T.table_collation
470 T.table_schema = '{$ce->database()}' -- COLLATE utf8_general_ci
472 T.table_name = '{$tbl}' -- COLLATE utf8_general_ci
477 if($ce->csname == 'utf8' && $ce->collatename == 'utf8_general_ci'){
478 echo "$tbl is Already utf8 \n";
481 //as the default collation for stored procedure parameters is utf8_general_ci and you can't mix collations.
483 $ce = DB_DataObject::factory('core_enum');
484 $ce->query("ALTER TABLE {$tbl} CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
485 echo "FIXED utf8 on {$tbl}\n";