UpdateDatabase/MysqlLinks.php
[Pman.Core] / UpdateDatabase / MysqlLinks.php
1 <?php
2 /**
3  * our standard code relies on links.ini files for the relationships in mysql.
4  *
5  * as we use 'loose' relationships - eg. we allow '0' as a missing link mysql FORIEGN KEYS do not really work.
6  *
7  * There are a couple of ideas behind this code.
8  *
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.
12  *
13  * b) generate triggers? to protect against updates to the database..
14  *
15  *  -- stored procedures are named
16  *     {tablename}_before_{insert|delete|update}
17  *     
18  *  
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}
25  *
26  *
27  * ------- Importing with triggers disabled.
28  *
29  *  SET @DISABLE_TRIGGER=1; (or anything you like except NULL) 
30  *  do imports
31  * SET @DISABLE_TRIGGER=NULL;
32  *
33  * ------ Call a method disabling a particular set of triggers
34  *  SET @DISABLE_TRIGGER_the_table_name=1; (or anything you like except NULL) 
35  *  do action
36  *  SET @DISABLE_TRIGGER_the_table_name=NULL;*
37  */
38
39 class Pman_Core_UpdateDatabase_MysqlLinks {
40     
41     var $dburl;
42     var $schema;
43     var $links;
44     
45     function __construct()
46     {
47           
48         $this->loadIniFiles();
49         $this->updateTableComments();
50        
51         $ff = HTML_FlexyFramework::get();
52         if (!empty($ff->Pman['enable_trigger_tests'])) {
53             
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.
56             
57             $this->createDeleteTriggers();
58             $this->createInsertTriggers();
59             $this->createUpdateTriggers();
60         }
61         
62         
63     }
64     
65     function loadIniFiles()
66     {
67         // will create the combined ini cache file for the running user.
68         
69         $ff = HTML_FlexyFramework::get();
70         $ff->generateDataobjectsCache(true);
71         $this->dburl = parse_url($ff->database);
72         
73         $dbini = 'ini_'. basename($this->dburl['path']);
74         
75         
76         $iniCache = $ff->DB_DataObject[$dbini];
77         
78         $this->schema = parse_ini_file($iniCache, true);
79         $this->links = parse_ini_file(preg_replace('/\.ini$/', '.links.ini', $iniCache), true);
80         
81
82         
83     }
84     function updateTableComments()
85     {
86         foreach($this->links as $tbl =>$map) {
87             $this->updateTableComment($tbl, $map);
88             
89         }
90         
91         
92     }
93     
94     function updateTableComment($tbl, $map)
95     {
96          
97         
98         if (!isset($this->schema[$tbl])) {
99             echo "Skip $tbl = table does not exist in schema\n";
100             return;
101         }
102         
103         
104         $q = DB_DAtaObject::factory('core_enum');
105         $q->query("SELECT
106                      TABLE_COMMENT
107                     FROM
108                         information_schema.TABLES
109                     WHERE
110                         TABLE_SCHEMA = '{$q->escape($q->database())}'
111                         AND
112                         TABLE_NAME = '{$q->escape($tbl)}'
113         ");
114         $q->fetch();
115         $tc = $q->TABLE_COMMENT;
116         //echo "$tbl: $tc\n\n";
117         if (!empty($q->TABLE_COMMENT)) {
118             //var_dump($tc);
119             $tc = trim(preg_replace('/FK\([^)]+\)/', '' , $q->TABLE_COMMENT));
120             //var_dump($tc);exit;
121             // strip out the old FC(....) 
122                         
123         }
124         $fks = array();
125         foreach($map as $k=>$v) {
126             $fks[] = "$k=$v";
127         }
128         $fkstr = $tc . ' FK(' . implode("\n", $fks) .')';
129         if ($q->TABLE_COMMENT == $fkstr) {
130             return;
131         }
132         
133         $q = DB_DAtaObject::factory('core_enum');
134         $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
135         
136         
137         
138     }
139     
140     function createDeleteTriggers()
141     {
142         
143         // this should only be enabled if the project settings are configured..
144         
145        
146         
147         // delete triggers on targets -
148         // if you delete a company, and a person points to it, then it should fire an error...
149         
150         
151         
152         
153         // create a list of source/targets from $this->links
154         
155                 
156         $revmap = array();
157         foreach($this->links as $tbl => $map) {
158             if (!isset($this->schema[$tbl])) {
159                 continue;
160             }
161             foreach($map as $k =>$v) {
162                 list ($tname, $tcol) = explode(':', $v);
163                 
164                 
165                 if (!isset($revmap[$tname])) {
166                     $revmap[$tname] = array();
167                 }
168                 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
169             }
170         }
171         
172         
173         
174         
175         foreach($revmap as $target_table => $sources) {
176             
177             
178             // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
179             
180             if (!isset($this->schema[$target_table])) {
181                 echo "Skip $target_table  = table does not exist in schema\n";
182                 continue;
183             }
184         
185             
186             
187             $q = DB_DataObject::factory('core_enum');
188             $q->query("
189                 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
190             ");
191             
192             $trigger = "
193              
194             CREATE TRIGGER `{$target_table}_before_delete`
195                 BEFORE DELETE ON `{$target_table}`
196             FOR EACH ROW
197             BEGIN
198                 DECLARE mid INT(11);
199                 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN  
200                
201             ";
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);
206                 $trigger .="
207                     SET mid = 0;
208                     IF OLD.{$target_col} > 0 THEN 
209                         SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
210                         IF mid > 0 THEN   
211                            UPDATE `$err` SET x = 1;
212                         END IF;
213                     END IF;
214                 ";
215             }
216             
217             $ar = $this->listTriggerFunctions($tbl, 'delete');
218             foreach($ar as $fn=>$col) {
219                 $trigger .= "
220                     CALL $fn( OLD.{$col});
221                 ";
222             }
223             
224             $trigger .= "
225                 END IF;
226             END 
227            
228             ";
229             
230             //DB_DAtaObject::debugLevel(1);
231             $q = DB_DataObject::factory('core_enum');
232             $q->query($trigger);
233              echo "CREATED TRIGGER {$target_table}_before_delete\n";
234         }
235         
236         
237         // inserting - row should not point to a reference that does not exist...
238         
239         
240         
241         
242     }
243     function createInsertTriggers()
244     {
245         foreach($this->links as $tbl => $map) {
246             if (!isset($this->schema[$tbl])) {
247                 continue;
248             }
249             
250             $q = DB_DataObject::factory('core_enum');
251             $q->query("
252                 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
253             ");
254             
255             $trigger = "
256              
257             CREATE TRIGGER `{$tbl}_before_insert`
258                 BEFORE INSERT ON `{$tbl}`
259             FOR EACH ROW
260             BEGIN
261                DECLARE mid INT(11);
262                 IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN 
263                
264             ";
265             $has_checks=  false;
266             
267             foreach($map as $source_col=>$target) {
268                 // check that source_col exists in schema.
269                 if (!isset($this->schema[$tbl][$source_col])) {
270                     continue;
271                 }
272                 
273                 
274                 $source_tbl = $tbl;
275                 list($target_table , $target_col) = explode(':', $target);
276                 
277                 if (!isset($this->schema[$target_table])) {
278                     // skip... target table does not exist
279                     continue;
280                 }
281                 
282                 
283                 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
284                 $trigger .="
285                     SET mid = 0;
286                     if NEW.{$source_col} > 0 THEN
287                         SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
288                         IF mid < 1 THEN
289                             UPDATE `$err` SET x = 1;
290                         END IF;
291                        
292                     END IF;
293                 ";
294                 $has_checks=  true;
295                 
296                 
297             }
298             
299             $ar = $this->listTriggerFunctions($tbl, 'insert');
300             foreach($ar as $fn=>$col) {
301                 $trigger .= "
302                     CALL $fn( NEW.{$col});
303                 ";
304                 $has_checks=  true;
305             }
306             
307             $trigger .= "
308                 END IF;
309             END 
310            
311             ";
312             
313             if (!$has_checks) {
314                 echo "SKIP TRIGGER {$tbl}_before_insert (missing links)\n";
315                 return;
316             }
317             //echo $trigger; exit;
318             //DB_DAtaObject::debugLevel(1);
319             $q = DB_DataObject::factory('core_enum');
320             $q->query($trigger);
321             echo "CREATED TRIGGER {$tbl}_before_insert\n";
322             
323             
324             
325             
326             
327             
328             
329         }
330         
331         
332         
333     }
334      function createUpdateTriggers()
335     {
336         foreach($this->links as $tbl => $map) {
337             if (!isset($this->schema[$tbl])) {
338                 continue;
339             }
340             
341             $q = DB_DataObject::factory('core_enum');
342             $q->query("
343                 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
344             ");
345             
346             $trigger = "
347              
348             CREATE TRIGGER `{$tbl}_before_update`
349                 BEFORE UPDATE ON `{$tbl}`
350             FOR EACH ROW
351             BEGIN
352                DECLARE mid INT(11);
353                IF (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$tbl} IS NULL ) THEN  
354                
355             ";
356             $has_checks=  false;
357             $err[] = array();
358             foreach($map as $source_col=>$target) {
359                 // check that source_col exists in schema.
360                 if (!isset($this->schema[$tbl][$source_col])) {
361                     $err[] = "SOURCE MISSING: $source_col => $target";
362                     continue;
363                 }
364                 
365                 
366                 $source_tbl = $tbl;
367                 list($target_table , $target_col) = explode(':', $target);
368                 
369                 if (!isset($this->schema[$target_table])) {
370                     // skip... target table does not exist
371                     $err[] = "TARGET MISSING: $source_col => $target";
372                     continue;
373                 }
374                 
375                 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
376                 $trigger .="
377                     SET mid = 0;
378                     if NEW.{$source_col} > 0 THEN
379                         SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
380                         IF mid < 1 THEN
381                             UPDATE `$err` SET x = 1;
382                         END IF;
383                        
384                     END IF;
385                 ";
386                 $has_checks=  true;
387             }
388             $ar = $this->listTriggerFunctions($tbl, 'update');
389             foreach($ar as $fn=>$col) {
390                 $trigger .= "
391                     CALL $fn(OLD.{$col}, NEW.{$col});
392                 ";
393                 $has_checks=  true;
394             }
395             
396             $trigger .= "
397                 END IF;
398             END 
399            
400             ";
401             if (!$has_checks) {
402                 echo "SKIP TRIGGER {$tbl}_before_update (missing " . implode($errs) . ")\n";
403                 return;
404             }
405             
406             //echo $trigger; exit;
407             //DB_DAtaObject::debugLevel(1);
408             $q = DB_DataObject::factory('core_enum');
409             $q->query($trigger);
410             echo "CREATED TRIGGER {$tbl}_before_update\n";
411             
412             
413             
414             
415             
416             
417             
418         }
419         
420         
421         
422     }
423     /**
424      * check the information schema for any methods that match the trigger criteria.
425      *   -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
426      *   -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
427      *   -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
428      *
429      *
430      */
431     // type = update/insert/delete
432     
433     function listTriggerFunctions($table, $type)
434     {
435         static $cache = array();
436         if (!isset($cache[$table])) {
437             $cache[$table] = array();
438             $q = DB_DAtaObject::factory('core_enum');
439             $q->query("SELECT
440                             SPECIFIC_NAME
441                         FROM
442                             information_schema.ROUTINES
443                         WHERE
444                             ROUTINE_SCHEMA = '{$q->escape($q->database())}'
445                             AND
446                             ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_")  . "%'
447                             AND
448                             ROUTINE_TYPE = 'PROCEDURE'
449                             
450             ");
451             while ($q->fetch()) {
452                 $cache[$table][] = $q->SPECIFIC_NAME;
453             }
454             
455         }
456         // now see which of the procedures match the specification..
457         $ret = array();
458         foreach($cache[$table] as $cname) {
459             $bits = explode("_before_{$type}_", $cname);
460             if (count($bits) < 2) {
461                 continue;
462             }
463             $ret[$cname] = $bits[1];
464         }
465         return $ret;
466     }
467         
468     
469     
470 }
471