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