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}`
255 if (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN
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});
301 //echo $trigger; exit;
302 //DB_DAtaObject::debugLevel(1);
303 $q = DB_DataObject::factory('core_enum');
305 echo "CREATED TRIGGER {$tbl}_before_insert\n";
318 function createUpdateTriggers()
320 foreach($this->links as $tbl => $map) {
321 if (!isset($this->schema[$tbl])) {
325 $q = DB_DataObject::factory('core_enum');
327 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
332 CREATE TRIGGER `{$tbl}_before_update`
333 BEFORE UPDATE ON `{$tbl}`
340 foreach($map as $source_col=>$target) {
341 // check that source_col exists in schema.
342 if (!isset($this->schema[$tbl][$source_col])) {
348 list($target_table , $target_col) = explode(':', $target);
350 if (!isset($this->schema[$target_table])) {
351 // skip... target table does not exist
355 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
358 if NEW.{$source_col} > 0 THEN
359 SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
361 UPDATE `$err` SET x = 1;
367 $ar = $this->listTriggerFunctions($tbl, 'update');
368 foreach($ar as $fn=>$col) {
370 CALL $fn(OLD.{$col}, NEW.{$col});
378 //echo $trigger; exit;
379 //DB_DAtaObject::debugLevel(1);
380 $q = DB_DataObject::factory('core_enum');
382 echo "CREATED TRIGGER {$tbl}_before_update\n";
396 * check the information schema for any methods that match the trigger criteria.
397 * -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
398 * -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
399 * -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
403 // type = update/insert/delete
405 function listTriggerFunctions($table, $type)
407 static $cache = array();
408 if (!isset($cache[$table])) {
409 $cache[$table] = array();
410 $q = DB_DAtaObject::factory('core_enum');
414 information_schema.ROUTINES
416 ROUTINE_SCHEMA = '{$q->escape($q->database())}'
418 ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_") . "%'
420 ROUTINE_TYPE = 'PROCEDURE'
423 while ($q->fetch()) {
424 $cache[$table][] = $q->SPECIFIC_NAME;
428 // now see which of the procedures match the specification..
430 foreach($cache[$table] as $cname) {
431 $bits = explode("_before_{$type}_", $cname);
432 if (count($bits) < 2) {
435 $ret[$cname] = $bits[1];
440 function updateCharacterSet()
442 foreach (array_keys($this->schema) as $tbl){
444 if(strpos($tbl, '__keys') !== false ){
448 $ce = DB_DataObject::factory('core_enum');
452 CCSA.character_set_name csname,
453 CCSA.collation_name collatename
455 information_schema.`TABLES` T,
456 information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
458 CCSA.collation_name = T.table_collation
460 T.table_schema = '{$ce->database()}' -- COLLATE utf8_unicode_ci
462 T.table_name = '{$tbl}' -- COLLATE utf8_unicode_ci
467 if($ce->csname == 'utf8' && $ce->collatename == 'utf8_unicode_ci'){
468 echo "$tbl is Already utf8 \n";
472 $ce = DB_DataObject::factory('core_enum');
473 $ce->query("ALTER TABLE {$tbl} CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci");
474 echo "FIXED utf8 on {$tbl}\n";