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();
52 $this->updateEngine();
54 $ff = HTML_FlexyFramework::get();
55 if (!empty($ff->Pman['enable_trigger_tests'])) {
57 // note we may want to override some of these... - to do special triggers..
58 // as you can only have one trigger per table for each action.
60 $this->createDeleteTriggers();
61 $this->createInsertTriggers();
62 $this->createUpdateTriggers();
68 function loadIniFiles()
70 // will create the combined ini cache file for the running user.
72 $ff = HTML_FlexyFramework::get();
73 $ff->generateDataobjectsCache(true);
74 $this->dburl = parse_url($ff->database);
76 $dbini = 'ini_'. basename($this->dburl['path']);
79 $iniCache = $ff->DB_DataObject[$dbini];
81 $this->schema = parse_ini_file($iniCache, true);
82 $this->links = parse_ini_file(preg_replace('/\.ini$/', '.links.ini', $iniCache), true);
87 function updateTableComments()
89 foreach($this->links as $tbl =>$map) {
90 $this->updateTableComment($tbl, $map);
97 function updateTableComment($tbl, $map)
101 if (!isset($this->schema[$tbl])) {
102 echo "Skip $tbl = table does not exist in schema\n";
107 $q = DB_DAtaObject::factory('core_enum');
111 information_schema.TABLES
113 TABLE_SCHEMA = '{$q->escape($q->database())}'
115 TABLE_NAME = '{$q->escape($tbl)}'
118 $tc = $q->TABLE_COMMENT;
119 //echo "$tbl: $tc\n\n";
120 if (!empty($q->TABLE_COMMENT)) {
122 $tc = trim(preg_replace('/FK\([^)]+\)/', '' , $q->TABLE_COMMENT));
123 //var_dump($tc);exit;
124 // strip out the old FC(....)
128 foreach($map as $k=>$v) {
131 $fkstr = $tc . ' FK(' . implode("\n", $fks) .')';
132 if ($q->TABLE_COMMENT == $fkstr) {
136 $q = DB_DAtaObject::factory('core_enum');
137 $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
143 function createDeleteTriggers()
146 // this should only be enabled if the project settings are configured..
150 // delete triggers on targets -
151 // if you delete a company, and a person points to it, then it should fire an error...
156 // create a list of source/targets from $this->links
160 foreach($this->links as $tbl => $map) {
161 if (!isset($this->schema[$tbl])) {
164 foreach($map as $k =>$v) {
165 list ($tname, $tcol) = explode(':', $v);
168 if (!isset($revmap[$tname])) {
169 $revmap[$tname] = array();
171 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
178 foreach($revmap as $target_table => $sources) {
181 // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
183 if (!isset($this->schema[$target_table])) {
184 echo "Skip $target_table = table does not exist in schema\n";
190 $q = DB_DataObject::factory('core_enum');
192 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
197 CREATE TRIGGER `{$target_table}_before_delete`
198 BEFORE DELETE ON `{$target_table}`
202 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN
205 foreach($sources as $source=>$target) {
206 list($source_table , $source_col) = explode(':', $source);
207 list($target_table , $target_col) = explode(':', $target);
208 $err = substr("Failed Delete {$target_table} refs {$source_table}:{$source_col}", 0, 64);
211 IF OLD.{$target_col} > 0 THEN
212 SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
214 UPDATE `$err` SET x = 1;
220 $ar = $this->listTriggerFunctions($tbl, 'delete');
221 foreach($ar as $fn=>$col) {
223 CALL $fn( OLD.{$col});
233 //DB_DAtaObject::debugLevel(1);
234 $q = DB_DataObject::factory('core_enum');
236 echo "CREATED TRIGGER {$target_table}_before_delete\n";
240 // inserting - row should not point to a reference that does not exist...
246 function createInsertTriggers()
248 foreach($this->links as $tbl => $map) {
249 if (!isset($this->schema[$tbl])) {
253 $q = DB_DataObject::factory('core_enum');
255 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
260 CREATE TRIGGER `{$tbl}_before_insert`
261 BEFORE INSERT ON `{$tbl}`
265 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN
268 foreach($map as $source_col=>$target) {
269 // check that source_col exists in schema.
270 if (!isset($this->schema[$tbl][$source_col])) {
276 list($target_table , $target_col) = explode(':', $target);
278 if (!isset($this->schema[$target_table])) {
279 // skip... target table does not exist
284 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
287 if NEW.{$source_col} > 0 THEN
288 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
290 UPDATE `$err` SET x = 1;
299 $ar = $this->listTriggerFunctions($tbl, 'insert');
300 foreach($ar as $fn=>$col) {
302 CALL $fn( NEW.{$col});
311 //echo $trigger; exit;
312 //DB_DAtaObject::debugLevel(1);
313 $q = DB_DataObject::factory('core_enum');
315 echo "CREATED TRIGGER {$tbl}_before_insert\n";
328 function createUpdateTriggers()
330 foreach($this->links as $tbl => $map) {
331 if (!isset($this->schema[$tbl])) {
335 $q = DB_DataObject::factory('core_enum');
337 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
342 CREATE TRIGGER `{$tbl}_before_update`
343 BEFORE UPDATE ON `{$tbl}`
347 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN
350 foreach($map as $source_col=>$target) {
351 // check that source_col exists in schema.
352 if (!isset($this->schema[$tbl][$source_col])) {
358 list($target_table , $target_col) = explode(':', $target);
360 if (!isset($this->schema[$target_table])) {
361 // skip... target table does not exist
365 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
368 if NEW.{$source_col} > 0 THEN
369 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
371 UPDATE `$err` SET x = 1;
377 $ar = $this->listTriggerFunctions($tbl, 'update');
378 foreach($ar as $fn=>$col) {
380 CALL $fn(OLD.{$col}, NEW.{$col});
389 //echo $trigger; exit;
390 //DB_DAtaObject::debugLevel(1);
391 $q = DB_DataObject::factory('core_enum');
393 echo "CREATED TRIGGER {$tbl}_before_update\n";
407 * check the information schema for any methods that match the trigger criteria.
408 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
409 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
410 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
414 // type = update/insert/delete
416 function listTriggerFunctions($table, $type)
418 static $cache = array();
419 if (!isset($cache[$table])) {
420 $cache[$table] = array();
421 $q = DB_DAtaObject::factory('core_enum');
425 information_schema.ROUTINES
427 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
429 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
431 ROUTINE_TYPE = 'PROCEDURE'
434 while ($q->fetch()) {
435 $cache[$table][] = $q->SPECIFIC_NAME;
439 // now see which of the procedures match the specification..
441 foreach($cache[$table] as $cname) {
442 $bits = explode("_before_{$type}_", $cname);
443 if (count($bits) < 2) {
446 $ret[$cname] = $bits[1];