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