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