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