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