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();
41 $ff = HTML_FlexyFramework::get();
42 if (!empty($ff->Pman['enable_trigger_tests'])) {
44 // note we may want to override some of these... - to do special triggers..
45 // as you can only have one trigger per table for each action.
47 $this->createDeleteTriggers();
48 $this->createInsertTriggers();
49 $this->createUpdateTriggers();
55 function loadIniFiles()
57 // will create the combined ini cache file for the running user.
59 $ff = HTML_FlexyFramework::get();
60 $ff->generateDataobjectsCache(true);
61 $this->dburl = parse_url($ff->database);
63 $dbini = 'ini_'. basename($this->dburl['path']);
66 $iniCache = $ff->DB_DataObject[$dbini];
68 $this->schema = parse_ini_file($iniCache, true);
69 $this->links = parse_ini_file(preg_replace('/\.ini$/', '.links.ini', $iniCache), true);
74 function updateTableComments()
76 foreach($this->links as $tbl =>$map) {
77 $this->updateTableComment($tbl, $map);
84 function updateTableComment($tbl, $map)
88 if (!isset($this->schema[$tbl])) {
89 echo "Skip $tbl = table does not exist in schema\n";
94 $q = DB_DAtaObject::factory('core_enum');
98 information_schema.TABLES
100 TABLE_SCHEMA = '{$q->escape($q->database())}'
102 TABLE_NAME = '{$q->escape($tbl)}'
105 $tc = $q->TABLE_COMMENT;
106 //echo "$tbl: $tc\n\n";
107 if (!empty($q->TABLE_COMMENT)) {
109 $tc = trim(preg_replace('/FK\([^)]+\)/', '' , $q->TABLE_COMMENT));
110 //var_dump($tc);exit;
111 // strip out the old FC(....)
115 foreach($map as $k=>$v) {
118 $fkstr = $tc . ' FK(' . implode("\n", $fks) .')';
119 if ($q->TABLE_COMMENT == $fkstr) {
123 echo "$fkstr \n $tbl";
125 $q = DB_DAtaObject::factory('core_enum');
126 $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
132 function createDeleteTriggers()
135 // this should only be enabled if the project settings are configured..
139 // delete triggers on targets -
140 // if you delete a company, and a person points to it, then it should fire an error...
145 // create a list of source/targets from $this->links
149 foreach($this->links as $tbl => $map) {
150 if (!isset($this->schema[$tbl])) {
153 foreach($map as $k =>$v) {
154 list ($tname, $tcol) = explode(':', $v);
157 if (!isset($revmap[$tname])) {
158 $revmap[$tname] = array();
160 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
167 foreach($revmap as $target_table => $sources) {
170 // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
172 if (!isset($this->schema[$target_table])) {
173 echo "Skip $target_table = table does not exist in schema\n";
179 $q = DB_DataObject::factory('core_enum');
181 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
186 CREATE TRIGGER `{$target_table}_before_delete`
187 BEFORE DELETE ON `{$target_table}`
194 foreach($sources as $source=>$target) {
195 list($source_table , $source_col) = explode(':', $source);
196 list($target_table , $target_col) = explode(':', $target);
197 $err = substr("Failed Delete {$target_table} refs {$source_table}:{$source_col}", 0, 64);
200 IF OLD.{$target_col} > 0 THEN
201 SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
203 UPDATE `$err` SET x = 1;
209 $ar = $this->listTriggerFunctions($tbl, 'delete');
210 foreach($ar as $fn=>$col) {
212 CALL $fn( OLD.{$col});
221 //DB_DAtaObject::debugLevel(1);
222 $q = DB_DataObject::factory('core_enum');
224 echo "CREATED TRIGGER {$target_table}_before_delete\n";
228 // inserting - row should not point to a reference that does not exist...
234 function createInsertTriggers()
236 foreach($this->links as $tbl => $map) {
237 if (!isset($this->schema[$tbl])) {
241 $q = DB_DataObject::factory('core_enum');
243 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
248 CREATE TRIGGER `{$tbl}_before_insert`
249 BEFORE INSERT ON `{$tbl}`
256 foreach($map as $source_col=>$target) {
257 // check that source_col exists in schema.
258 if (!isset($this->schema[$tbl][$source_col])) {
264 list($target_table , $target_col) = explode(':', $target);
266 if (!isset($this->schema[$target_table])) {
267 // skip... target table does not exist
272 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
275 if NEW.{$source_col} > 0 THEN
276 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
278 UPDATE `$err` SET x = 1;
287 $ar = $this->listTriggerFunctions($tbl, 'insert');
288 foreach($ar as $fn=>$col) {
290 CALL $fn( NEW.{$col});
298 //echo $trigger; exit;
299 //DB_DAtaObject::debugLevel(1);
300 $q = DB_DataObject::factory('core_enum');
302 echo "CREATED TRIGGER {$tbl}_before_insert\n";
315 function createUpdateTriggers()
317 foreach($this->links as $tbl => $map) {
318 if (!isset($this->schema[$tbl])) {
322 $q = DB_DataObject::factory('core_enum');
324 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
329 CREATE TRIGGER `{$tbl}_before_update`
330 BEFORE UPDATE ON `{$tbl}`
337 foreach($map as $source_col=>$target) {
338 // check that source_col exists in schema.
339 if (!isset($this->schema[$tbl][$source_col])) {
345 list($target_table , $target_col) = explode(':', $target);
347 if (!isset($this->schema[$target_table])) {
348 // skip... target table does not exist
352 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
355 if NEW.{$source_col} > 0 THEN
356 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
358 UPDATE `$err` SET x = 1;
364 $ar = $this->listTriggerFunctions($tbl, 'update');
365 foreach($ar as $fn=>$col) {
367 CALL $fn(OLD.{$col}, NEW.{$col});
375 //echo $trigger; exit;
376 //DB_DAtaObject::debugLevel(1);
377 $q = DB_DataObject::factory('core_enum');
379 echo "CREATED TRIGGER {$tbl}_before_update\n";
393 * check the information schema for any methods that match the trigger criteria.
394 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
395 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
396 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
400 // type = update/insert/delete
402 function listTriggerFunctions($table, $type)
404 static $cache = array();
405 if (!isset($cache[$table])) {
406 $cache[$table] = array();
407 $q = DB_DAtaObject::factory('core_enum');
411 information_schema.ROUTINES
413 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
415 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
417 ROUTINE_TYPE = 'PROCEDURE'
420 while ($q->fetch()) {
421 $cache[$table][] = $q->SPECIFIC_NAME;
425 // now see which of the procedures match the specification..
427 foreach($cache[$table] as $cname) {
428 $bits = explode("_before_{$type}_", $cname);
429 if (count($bits) < 2) {
432 $ret[$cname] = $bits[1];