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 $ff = HTML_FlexyFramework::get();
52 if (!empty($ff->Pman['enable_trigger_tests'])) {
54 // note we may want to override some of these... - to do special triggers..
55 // as you can only have one trigger per table for each action.
57 $this->createDeleteTriggers();
58 $this->createInsertTriggers();
59 $this->createUpdateTriggers();
65 function loadIniFiles()
67 // will create the combined ini cache file for the running user.
69 $ff = HTML_FlexyFramework::get();
70 $ff->generateDataobjectsCache(true);
71 $this->dburl = parse_url($ff->database);
73 $dbini = 'ini_'. basename($this->dburl['path']);
76 $iniCache = $ff->DB_DataObject[$dbini];
78 $this->schema = parse_ini_file($iniCache, true);
79 $this->links = parse_ini_file(preg_replace('/\.ini$/', '.links.ini', $iniCache), true);
84 function updateTableComments()
86 foreach($this->links as $tbl =>$map) {
87 $this->updateTableComment($tbl, $map);
94 function updateTableComment($tbl, $map)
98 if (!isset($this->schema[$tbl])) {
99 echo "Skip $tbl = table does not exist in schema\n";
104 $q = DB_DAtaObject::factory('core_enum');
108 information_schema.TABLES
110 TABLE_SCHEMA = '{$q->escape($q->database())}'
112 TABLE_NAME = '{$q->escape($tbl)}'
115 $tc = $q->TABLE_COMMENT;
116 //echo "$tbl: $tc\n\n";
117 if (!empty($q->TABLE_COMMENT)) {
119 $tc = trim(preg_replace('/FK\([^)]+\)/', '' , $q->TABLE_COMMENT));
120 //var_dump($tc);exit;
121 // strip out the old FC(....)
125 foreach($map as $k=>$v) {
128 $fkstr = $tc . ' FK(' . implode("\n", $fks) .')';
129 if ($q->TABLE_COMMENT == $fkstr) {
133 $q = DB_DAtaObject::factory('core_enum');
134 $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
140 function createDeleteTriggers()
143 // this should only be enabled if the project settings are configured..
147 // delete triggers on targets -
148 // if you delete a company, and a person points to it, then it should fire an error...
153 // create a list of source/targets from $this->links
157 foreach($this->links as $tbl => $map) {
158 if (!isset($this->schema[$tbl])) {
161 foreach($map as $k =>$v) {
162 list ($tname, $tcol) = explode(':', $v);
165 if (!isset($revmap[$tname])) {
166 $revmap[$tname] = array();
168 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
175 foreach($revmap as $target_table => $sources) {
178 // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
180 if (!isset($this->schema[$target_table])) {
181 echo "Skip $target_table = table does not exist in schema\n";
187 $q = DB_DataObject::factory('core_enum');
189 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
194 CREATE TRIGGER `{$target_table}_before_delete`
195 BEFORE DELETE ON `{$target_table}`
199 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN
202 foreach($sources as $source=>$target) {
203 list($source_table , $source_col) = explode(':', $source);
204 list($target_table , $target_col) = explode(':', $target);
205 $err = substr("Failed Delete {$target_table} refs {$source_table}:{$source_col}", 0, 64);
208 IF OLD.{$target_col} > 0 THEN
209 SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
211 UPDATE `$err` SET x = 1;
217 $ar = $this->listTriggerFunctions($tbl, 'delete');
218 foreach($ar as $fn=>$col) {
220 CALL $fn( OLD.{$col});
230 //DB_DAtaObject::debugLevel(1);
231 $q = DB_DataObject::factory('core_enum');
233 echo "CREATED TRIGGER {$target_table}_before_delete\n";
237 // inserting - row should not point to a reference that does not exist...
243 function createInsertTriggers()
245 foreach($this->links as $tbl => $map) {
246 if (!isset($this->schema[$tbl])) {
250 $q = DB_DataObject::factory('core_enum');
252 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
257 CREATE TRIGGER `{$tbl}_before_insert`
258 BEFORE INSERT ON `{$tbl}`
262 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN
265 foreach($map as $source_col=>$target) {
266 // check that source_col exists in schema.
267 if (!isset($this->schema[$tbl][$source_col])) {
273 list($target_table , $target_col) = explode(':', $target);
275 if (!isset($this->schema[$target_table])) {
276 // skip... target table does not exist
281 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
284 if NEW.{$source_col} > 0 THEN
285 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
287 UPDATE `$err` SET x = 1;
296 $ar = $this->listTriggerFunctions($tbl, 'insert');
297 foreach($ar as $fn=>$col) {
299 CALL $fn( NEW.{$col});
308 //echo $trigger; exit;
309 //DB_DAtaObject::debugLevel(1);
310 $q = DB_DataObject::factory('core_enum');
312 echo "CREATED TRIGGER {$tbl}_before_insert\n";
325 function createUpdateTriggers()
327 foreach($this->links as $tbl => $map) {
328 if (!isset($this->schema[$tbl])) {
332 $q = DB_DataObject::factory('core_enum');
334 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
339 CREATE TRIGGER `{$tbl}_before_update`
340 BEFORE UPDATE ON `{$tbl}`
344 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN
347 foreach($map as $source_col=>$target) {
348 // check that source_col exists in schema.
349 if (!isset($this->schema[$tbl][$source_col])) {
355 list($target_table , $target_col) = explode(':', $target);
357 if (!isset($this->schema[$target_table])) {
358 // skip... target table does not exist
362 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
365 if NEW.{$source_col} > 0 THEN
366 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
368 UPDATE `$err` SET x = 1;
374 $ar = $this->listTriggerFunctions($tbl, 'update');
375 foreach($ar as $fn=>$col) {
377 CALL $fn(OLD.{$col}, NEW.{$col});
386 //echo $trigger; exit;
387 //DB_DAtaObject::debugLevel(1);
388 $q = DB_DataObject::factory('core_enum');
390 echo "CREATED TRIGGER {$tbl}_before_update\n";
404 * check the information schema for any methods that match the trigger criteria.
405 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
406 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
407 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
411 // type = update/insert/delete
413 function listTriggerFunctions($table, $type)
415 static $cache = array();
416 if (!isset($cache[$table])) {
417 $cache[$table] = array();
418 $q = DB_DAtaObject::factory('core_enum');
422 information_schema.ROUTINES
424 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
426 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
428 ROUTINE_TYPE = 'PROCEDURE'
431 while ($q->fetch()) {
432 $cache[$table][] = $q->SPECIFIC_NAME;
436 // now see which of the procedures match the specification..
438 foreach($cache[$table] as $cname) {
439 $bits = explode("_before_{$type}_", $cname);
440 if (count($bits) < 2) {
443 $ret[$cname] = $bits[1];