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}
30 class Pman_Core_UpdateDatabase_MysqlLinks {
36 function __construct()
39 $this->loadIniFiles();
40 $this->updateTableComments();
42 $this->updateCharacterSet();
44 $ff = HTML_FlexyFramework::get();
45 if (!empty($ff->Pman['enable_trigger_tests'])) {
47 // note we may want to override some of these... - to do special triggers..
48 // as you can only have one trigger per table for each action.
50 $this->createDeleteTriggers();
51 $this->createInsertTriggers();
52 $this->createUpdateTriggers();
58 function loadIniFiles()
60 // will create the combined ini cache file for the running user.
62 $ff = HTML_FlexyFramework::get();
63 $ff->generateDataobjectsCache(true);
64 $this->dburl = parse_url($ff->database);
66 $dbini = 'ini_'. basename($this->dburl['path']);
69 $iniCache = $ff->DB_DataObject[$dbini];
71 $this->schema = parse_ini_file($iniCache, true);
72 $this->links = parse_ini_file(preg_replace('/\.ini$/', '.links.ini', $iniCache), true);
77 function updateTableComments()
79 foreach($this->links as $tbl =>$map) {
80 $this->updateTableComment($tbl, $map);
87 function updateTableComment($tbl, $map)
91 if (!isset($this->schema[$tbl])) {
92 echo "Skip $tbl = table does not exist in schema\n";
97 $q = DB_DAtaObject::factory('core_enum');
101 information_schema.TABLES
103 TABLE_SCHEMA = '{$q->escape($q->database())}'
105 TABLE_NAME = '{$q->escape($tbl)}'
108 $tc = $q->TABLE_COMMENT;
109 //echo "$tbl: $tc\n\n";
110 if (!empty($q->TABLE_COMMENT)) {
112 $tc = trim(preg_replace('/FK\([^)]+\)/', '' , $q->TABLE_COMMENT));
113 //var_dump($tc);exit;
114 // strip out the old FC(....)
118 foreach($map as $k=>$v) {
121 $fkstr = $tc . ' FK(' . implode("\n", $fks) .')';
122 if ($q->TABLE_COMMENT == $fkstr) {
126 $q = DB_DAtaObject::factory('core_enum');
127 $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
133 function createDeleteTriggers()
136 // this should only be enabled if the project settings are configured..
140 // delete triggers on targets -
141 // if you delete a company, and a person points to it, then it should fire an error...
146 // create a list of source/targets from $this->links
150 foreach($this->links as $tbl => $map) {
151 if (!isset($this->schema[$tbl])) {
154 foreach($map as $k =>$v) {
155 list ($tname, $tcol) = explode(':', $v);
158 if (!isset($revmap[$tname])) {
159 $revmap[$tname] = array();
161 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
168 foreach($revmap as $target_table => $sources) {
171 // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
173 if (!isset($this->schema[$target_table])) {
174 echo "Skip $target_table = table does not exist in schema\n";
180 $q = DB_DataObject::factory('core_enum');
182 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
187 CREATE TRIGGER `{$target_table}_before_delete`
188 BEFORE DELETE ON `{$target_table}`
192 if (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN
195 foreach($sources as $source=>$target) {
196 list($source_table , $source_col) = explode(':', $source);
197 list($target_table , $target_col) = explode(':', $target);
198 $err = substr("Failed Delete {$target_table} refs {$source_table}:{$source_col}", 0, 64);
201 IF OLD.{$target_col} > 0 THEN
202 SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
204 UPDATE `$err` SET x = 1;
210 $ar = $this->listTriggerFunctions($tbl, 'delete');
211 foreach($ar as $fn=>$col) {
213 CALL $fn( OLD.{$col});
223 //DB_DAtaObject::debugLevel(1);
224 $q = DB_DataObject::factory('core_enum');
226 echo "CREATED TRIGGER {$target_table}_before_delete\n";
230 // inserting - row should not point to a reference that does not exist...
236 function createInsertTriggers()
238 foreach($this->links as $tbl => $map) {
239 if (!isset($this->schema[$tbl])) {
243 $q = DB_DataObject::factory('core_enum');
245 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
250 CREATE TRIGGER `{$tbl}_before_insert`
251 BEFORE INSERT ON `{$tbl}`
258 foreach($map as $source_col=>$target) {
259 // check that source_col exists in schema.
260 if (!isset($this->schema[$tbl][$source_col])) {
266 list($target_table , $target_col) = explode(':', $target);
268 if (!isset($this->schema[$target_table])) {
269 // skip... target table does not exist
274 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
277 if NEW.{$source_col} > 0 THEN
278 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
280 UPDATE `$err` SET x = 1;
289 $ar = $this->listTriggerFunctions($tbl, 'insert');
290 foreach($ar as $fn=>$col) {
292 CALL $fn( NEW.{$col});
300 //echo $trigger; exit;
301 //DB_DAtaObject::debugLevel(1);
302 $q = DB_DataObject::factory('core_enum');
304 echo "CREATED TRIGGER {$tbl}_before_insert\n";
317 function createUpdateTriggers()
319 foreach($this->links as $tbl => $map) {
320 if (!isset($this->schema[$tbl])) {
324 $q = DB_DataObject::factory('core_enum');
326 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
331 CREATE TRIGGER `{$tbl}_before_update`
332 BEFORE UPDATE ON `{$tbl}`
339 foreach($map as $source_col=>$target) {
340 // check that source_col exists in schema.
341 if (!isset($this->schema[$tbl][$source_col])) {
347 list($target_table , $target_col) = explode(':', $target);
349 if (!isset($this->schema[$target_table])) {
350 // skip... target table does not exist
354 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
357 if NEW.{$source_col} > 0 THEN
358 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
360 UPDATE `$err` SET x = 1;
366 $ar = $this->listTriggerFunctions($tbl, 'update');
367 foreach($ar as $fn=>$col) {
369 CALL $fn(OLD.{$col}, NEW.{$col});
377 //echo $trigger; exit;
378 //DB_DAtaObject::debugLevel(1);
379 $q = DB_DataObject::factory('core_enum');
381 echo "CREATED TRIGGER {$tbl}_before_update\n";
395 * check the information schema for any methods that match the trigger criteria.
396 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
397 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
398 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
402 // type = update/insert/delete
404 function listTriggerFunctions($table, $type)
406 static $cache = array();
407 if (!isset($cache[$table])) {
408 $cache[$table] = array();
409 $q = DB_DAtaObject::factory('core_enum');
413 information_schema.ROUTINES
415 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
417 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
419 ROUTINE_TYPE = 'PROCEDURE'
422 while ($q->fetch()) {
423 $cache[$table][] = $q->SPECIFIC_NAME;
427 // now see which of the procedures match the specification..
429 foreach($cache[$table] as $cname) {
430 $bits = explode("_before_{$type}_", $cname);
431 if (count($bits) < 2) {
434 $ret[$cname] = $bits[1];
439 function updateCharacterSet()
441 foreach (array_keys($this->schema) as $tbl){
443 if(strpos($tbl, '__keys') !== false ){
447 $ce = DB_DataObject::factory('core_enum');
451 CCSA.character_set_name csname,
452 CCSA.collation_name collatename
454 information_schema.`TABLES` T,
455 information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
457 CCSA.collation_name = T.table_collation
459 T.table_schema = '{$ce->database()}' -- COLLATE utf8_unicode_ci
461 T.table_name = '{$tbl}' -- COLLATE utf8_unicode_ci
466 if($ce->csname == 'utf8' && $ce->collatename == 'utf8_unicode_ci'){
467 echo "$tbl is Already utf8 \n";
471 $ce = DB_DataObject::factory('core_enum');
472 $ce->query("ALTER TABLE {$tbl} CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci");
473 echo "FIXED utf8 on {$tbl}\n";