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