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         $q = DB_DAtaObject::factory('core_enum');
124         $q->query("ALTER TABLE $tbl COMMENT = '{$q->escape($fkstr)}'");
125         
126         
127         
128     }
129     
130     function createDeleteTriggers()
131     {
132         
133         // this should only be enabled if the project settings are configured..
134         
135        
136         
137         // delete triggers on targets -
138         // if you delete a company, and a person points to it, then it should fire an error...
139         
140         
141         
142         
143         // create a list of source/targets from $this->links
144         
145                 
146         $revmap = array();
147         foreach($this->links as $tbl => $map) {
148             if (!isset($this->schema[$tbl])) {
149                 continue;
150             }
151             foreach($map as $k =>$v) {
152                 list ($tname, $tcol) = explode(':', $v);
153                 
154                 
155                 if (!isset($revmap[$tname])) {
156                     $revmap[$tname] = array();
157                 }
158                 $revmap[$tname]["$tbl:$k"] = "$tname:$tcol";
159             }
160         }
161         
162         
163         
164         
165         foreach($revmap as $target_table => $sources) {
166             
167             
168             // throw example.. UPDATE `Error: invalid_id_test` SET x=1;
169             
170             if (!isset($this->schema[$target_table])) {
171                 echo "Skip $target_table  = table does not exist in schema\n";
172                 continue;
173             }
174         
175             
176             
177             $q = DB_DataObject::factory('core_enum');
178             $q->query("
179                 DROP TRIGGER IF EXISTS `{$target_table}_before_delete` ;
180             ");
181             
182             $trigger = "
183              
184             CREATE TRIGGER `{$target_table}_before_delete`
185                 BEFORE DELETE ON `{$target_table}`
186             FOR EACH ROW
187             BEGIN
188                DECLARE mid INT(11);
189              
190                
191             ";
192             foreach($sources as $source=>$target) {
193                 list($source_table , $source_col) = explode(':', $source);
194                 list($target_table , $target_col) = explode(':', $target);
195                 $err = substr("Failed Delete {$target_table} refs {$source_table}:{$source_col}", 0, 64);
196                 $trigger .="
197                     SET mid = 0;
198                     IF OLD.{$target_col} > 0 THEN 
199                         SELECT count(*) into mid FROM {$source_table} WHERE {$source_col} = OLD.{$target_col} LIMIT 1;
200                         IF mid > 0 THEN   
201                            UPDATE `$err` SET x = 1;
202                         END IF;
203                     END IF;
204                 ";
205             }
206             
207             $ar = $this->listTriggerFunctions($tbl, 'delete');
208             foreach($ar as $fn=>$col) {
209                 $trigger .= "
210                     CALL $fn( OLD.{$col});
211                 ";
212             }
213             
214             $trigger .= "
215             END 
216            
217             ";
218             
219             //DB_DAtaObject::debugLevel(1);
220             $q = DB_DataObject::factory('core_enum');
221             $q->query($trigger);
222              echo "CREATED TRIGGER {$target_table}_before_delete\n";
223         }
224         
225         
226         // inserting - row should not point to a reference that does not exist...
227         
228         
229         
230         
231     }
232     function createInsertTriggers()
233     {
234         foreach($this->links as $tbl => $map) {
235             if (!isset($this->schema[$tbl])) {
236                 continue;
237             }
238             
239             $q = DB_DataObject::factory('core_enum');
240             $q->query("
241                 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
242             ");
243             
244             $trigger = "
245              
246             CREATE TRIGGER `{$tbl}_before_insert`
247                 BEFORE INSERT ON `{$tbl}`
248             FOR EACH ROW
249             BEGIN
250                DECLARE mid INT(11);
251                
252                
253             ";
254             foreach($map as $source_col=>$target) {
255                 // check that source_col exists in schema.
256                 if (!isset($this->schema[$tbl][$source_col])) {
257                     continue;
258                 }
259                 
260                 
261                 $source_tbl = $tbl;
262                 list($target_table , $target_col) = explode(':', $target);
263                 
264                 if (!isset($this->schema[$target_table])) {
265                     // skip... target table does not exist
266                     continue;
267                 }
268                 
269                 
270                 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
271                 $trigger .="
272                     SET mid = 0;
273                     if NEW.{$source_col} > 0 THEN
274                         SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
275                         IF mid < 1 THEN
276                             UPDATE `$err` SET x = 1;
277                         END IF;
278                        
279                     END IF;
280                 ";
281                 
282                 
283                 
284             }
285             $ar = $this->listTriggerFunctions($tbl, 'insert');
286             foreach($ar as $fn=>$col) {
287                 $trigger .= "
288                     CALL $fn( NEW.{$col});
289                 ";
290             }
291             
292             $trigger .= "
293             END 
294            
295             ";
296             //echo $trigger; exit;
297             //DB_DAtaObject::debugLevel(1);
298             $q = DB_DataObject::factory('core_enum');
299             $q->query($trigger);
300             echo "CREATED TRIGGER {$tbl}_before_insert\n";
301             
302             
303             
304             
305             
306             
307             
308         }
309         
310         
311         
312     }
313      function createUpdateTriggers()
314     {
315         foreach($this->links as $tbl => $map) {
316             if (!isset($this->schema[$tbl])) {
317                 continue;
318             }
319             
320             $q = DB_DataObject::factory('core_enum');
321             $q->query("
322                 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
323             ");
324             
325             $trigger = "
326              
327             CREATE TRIGGER `{$tbl}_before_update`
328                 BEFORE UPDATE ON `{$tbl}`
329             FOR EACH ROW
330             BEGIN
331                DECLARE mid INT(11);
332                
333                
334             ";
335             foreach($map as $source_col=>$target) {
336                 // check that source_col exists in schema.
337                 if (!isset($this->schema[$tbl][$source_col])) {
338                     continue;
339                 }
340                 
341                 
342                 $source_tbl = $tbl;
343                 list($target_table , $target_col) = explode(':', $target);
344                 
345                 if (!isset($this->schema[$target_table])) {
346                     // skip... target table does not exist
347                     continue;
348                 }
349                 
350                 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
351                 $trigger .="
352                     SET mid = 0;
353                     if NEW.{$source_col} > 0 THEN
354                         SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
355                         IF mid < 1 THEN
356                             UPDATE `$err` SET x = 1;
357                         END IF;
358                        
359                     END IF;
360                 ";
361             }
362             $ar = $this->listTriggerFunctions($tbl, 'update');
363             foreach($ar as $fn=>$col) {
364                 $trigger .= "
365                     CALL $fn(OLD.{$col}, NEW.{$col});
366                 ";
367             }
368             
369             $trigger .= "
370             END 
371            
372             ";
373             //echo $trigger; exit;
374             //DB_DAtaObject::debugLevel(1);
375             $q = DB_DataObject::factory('core_enum');
376             $q->query($trigger);
377             echo "CREATED TRIGGER {$tbl}_before_update\n";
378             
379             
380             
381             
382             
383             
384             
385         }
386         
387         
388         
389     }
390     /**
391      * check the information schema for any methods that match the trigger criteria.
392      *   -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
393      *   -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
394      *   -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
395      *
396      *
397      */
398     // type = update/insert/delete
399     
400     function listTriggerFunctions($table, $type)
401     {
402         static $cache = array();
403         if (!isset($cache[$table])) {
404             $cache[$table] = array();
405             $q = DB_DAtaObject::factory('core_enum');
406             $q->query("SELECT
407                             SPECIFIC_NAME
408                         FROM
409                             information_schema.ROUTINES
410                         WHERE
411                             ROUTINE_SCHEMA = '{$q->escape($q->database())}'
412                             AND
413                             ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_")  . "%'
414                             AND
415                             ROUTINE_TYPE = 'PROCEDURE'
416                             
417             ");
418             while ($q->fetch()) {
419                 $cache[$table][] = $q->SPECIFIC_NAME;
420             }
421             
422         }
423         // now see which of the procedures match the specification..
424         $ret = array();
425         foreach($cache[$table] as $cname) {
426             $bits = explode("_before_{$type}_", $cname);
427             if (count($bits) < 2) {
428                 continue;
429             }
430             $ret[$cname] = $bits[1];
431         }
432         return $ret;
433     }
434         
435     
436 }
437