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}`
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});
222 //DB_DAtaObject::debugLevel(1);
223 $q = DB_DataObject::factory('core_enum');
225 echo "CREATED TRIGGER {$target_table}_before_delete\n";
229 // inserting - row should not point to a reference that does not exist...
235 function createInsertTriggers()
237 foreach($this->links as $tbl => $map) {
238 if (!isset($this->schema[$tbl])) {
242 $q = DB_DataObject::factory('core_enum');
244 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
249 CREATE TRIGGER `{$tbl}_before_insert`
250 BEFORE INSERT ON `{$tbl}`
257 foreach($map as $source_col=>$target) {
258 // check that source_col exists in schema.
259 if (!isset($this->schema[$tbl][$source_col])) {
265 list($target_table , $target_col) = explode(':', $target);
267 if (!isset($this->schema[$target_table])) {
268 // skip... target table does not exist
273 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
276 if NEW.{$source_col} > 0 THEN
277 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
279 UPDATE `$err` SET x = 1;
288 $ar = $this->listTriggerFunctions($tbl, 'insert');
289 foreach($ar as $fn=>$col) {
291 CALL $fn( NEW.{$col});
299 //echo $trigger; exit;
300 //DB_DAtaObject::debugLevel(1);
301 $q = DB_DataObject::factory('core_enum');
303 echo "CREATED TRIGGER {$tbl}_before_insert\n";
316 function createUpdateTriggers()
318 foreach($this->links as $tbl => $map) {
319 if (!isset($this->schema[$tbl])) {
323 $q = DB_DataObject::factory('core_enum');
325 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
330 CREATE TRIGGER `{$tbl}_before_update`
331 BEFORE UPDATE ON `{$tbl}`
338 foreach($map as $source_col=>$target) {
339 // check that source_col exists in schema.
340 if (!isset($this->schema[$tbl][$source_col])) {
346 list($target_table , $target_col) = explode(':', $target);
348 if (!isset($this->schema[$target_table])) {
349 // skip... target table does not exist
353 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
356 if NEW.{$source_col} > 0 THEN
357 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
359 UPDATE `$err` SET x = 1;
365 $ar = $this->listTriggerFunctions($tbl, 'update');
366 foreach($ar as $fn=>$col) {
368 CALL $fn(OLD.{$col}, NEW.{$col});
376 //echo $trigger; exit;
377 //DB_DAtaObject::debugLevel(1);
378 $q = DB_DataObject::factory('core_enum');
380 echo "CREATED TRIGGER {$tbl}_before_update\n";
394 * check the information schema for any methods that match the trigger criteria.
395 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
396 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
397 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
401 // type = update/insert/delete
403 function listTriggerFunctions($table, $type)
405 static $cache = array();
406 if (!isset($cache[$table])) {
407 $cache[$table] = array();
408 $q = DB_DAtaObject::factory('core_enum');
412 information_schema.ROUTINES
414 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
416 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
418 ROUTINE_TYPE = 'PROCEDURE'
421 while ($q->fetch()) {
422 $cache[$table][] = $q->SPECIFIC_NAME;
426 // now see which of the procedures match the specification..
428 foreach($cache[$table] as $cname) {
429 $bits = explode("_before_{$type}_", $cname);
430 if (count($bits) < 2) {
433 $ret[$cname] = $bits[1];
438 function updateCharacterSet()
440 foreach (array_keys($this->schema) as $tbl){
442 if(strpos($tbl, '__keys') !== false ){
446 echo "CALL mysql_change_charset('{$tbl}') \n";
449 $ce = DB_DataObject::factory('core_enum');
450 $ce->query("CALL mysql_change_charset('{$tbl}')");