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                 if (@DISABLE_TRIGGER IS NULL AND @DISABLE_TRIGGER_{$target_table} IS NULL ) THEN  
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 IF;
219             END 
220            
221             ";
222             
223             //DB_DAtaObject::debugLevel(1);
224             $q = DB_DataObject::factory('core_enum');
225             $q->query($trigger);
226              echo "CREATED TRIGGER {$target_table}_before_delete\n";
227         }
228         
229         
230         // inserting - row should not point to a reference that does not exist...
231         
232         
233         
234         
235     }
236     function createInsertTriggers()
237     {
238         foreach($this->links as $tbl => $map) {
239             if (!isset($this->schema[$tbl])) {
240                 continue;
241             }
242             
243             $q = DB_DataObject::factory('core_enum');
244             $q->query("
245                 DROP TRIGGER IF EXISTS `{$tbl}_before_insert` ;
246             ");
247             
248             $trigger = "
249              
250             CREATE TRIGGER `{$tbl}_before_insert`
251                 BEFORE INSERT ON `{$tbl}`
252             FOR EACH ROW
253             BEGIN
254                DECLARE mid INT(11);
255                
256                
257             ";
258             foreach($map as $source_col=>$target) {
259                 // check that source_col exists in schema.
260                 if (!isset($this->schema[$tbl][$source_col])) {
261                     continue;
262                 }
263                 
264                 
265                 $source_tbl = $tbl;
266                 list($target_table , $target_col) = explode(':', $target);
267                 
268                 if (!isset($this->schema[$target_table])) {
269                     // skip... target table does not exist
270                     continue;
271                 }
272                 
273                 
274                 $err = substr("Fail: INSERT referenced {$tbl}:{$source_col}", 0, 64);
275                 $trigger .="
276                     SET mid = 0;
277                     if NEW.{$source_col} > 0 THEN
278                         SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
279                         IF mid < 1 THEN
280                             UPDATE `$err` SET x = 1;
281                         END IF;
282                        
283                     END IF;
284                 ";
285                 
286                 
287                 
288             }
289             $ar = $this->listTriggerFunctions($tbl, 'insert');
290             foreach($ar as $fn=>$col) {
291                 $trigger .= "
292                     CALL $fn( NEW.{$col});
293                 ";
294             }
295             
296             $trigger .= "
297             END 
298            
299             ";
300             //echo $trigger; exit;
301             //DB_DAtaObject::debugLevel(1);
302             $q = DB_DataObject::factory('core_enum');
303             $q->query($trigger);
304             echo "CREATED TRIGGER {$tbl}_before_insert\n";
305             
306             
307             
308             
309             
310             
311             
312         }
313         
314         
315         
316     }
317      function createUpdateTriggers()
318     {
319         foreach($this->links as $tbl => $map) {
320             if (!isset($this->schema[$tbl])) {
321                 continue;
322             }
323             
324             $q = DB_DataObject::factory('core_enum');
325             $q->query("
326                 DROP TRIGGER IF EXISTS `{$tbl}_before_update` ;
327             ");
328             
329             $trigger = "
330              
331             CREATE TRIGGER `{$tbl}_before_update`
332                 BEFORE UPDATE ON `{$tbl}`
333             FOR EACH ROW
334             BEGIN
335                DECLARE mid INT(11);
336                
337                
338             ";
339             foreach($map as $source_col=>$target) {
340                 // check that source_col exists in schema.
341                 if (!isset($this->schema[$tbl][$source_col])) {
342                     continue;
343                 }
344                 
345                 
346                 $source_tbl = $tbl;
347                 list($target_table , $target_col) = explode(':', $target);
348                 
349                 if (!isset($this->schema[$target_table])) {
350                     // skip... target table does not exist
351                     continue;
352                 }
353                 
354                 $err = substr("Fail: UPDATE referenced {$tbl}:$source_col", 0, 64);
355                 $trigger .="
356                     SET mid = 0;
357                     if NEW.{$source_col} > 0 THEN
358                         SELECT {$target_col} into mid FROM {$target_table} WHERE {$target_col} = NEW.{$source_col} LIMIT 1;
359                         IF mid < 1 THEN
360                             UPDATE `$err` SET x = 1;
361                         END IF;
362                        
363                     END IF;
364                 ";
365             }
366             $ar = $this->listTriggerFunctions($tbl, 'update');
367             foreach($ar as $fn=>$col) {
368                 $trigger .= "
369                     CALL $fn(OLD.{$col}, NEW.{$col});
370                 ";
371             }
372             
373             $trigger .= "
374             END 
375            
376             ";
377             //echo $trigger; exit;
378             //DB_DAtaObject::debugLevel(1);
379             $q = DB_DataObject::factory('core_enum');
380             $q->query($trigger);
381             echo "CREATED TRIGGER {$tbl}_before_update\n";
382             
383             
384             
385             
386             
387             
388             
389         }
390         
391         
392         
393     }
394     /**
395      * check the information schema for any methods that match the trigger criteria.
396      *   -- {tablename}_trigger_{optional_string}_before_delete_{column_name}(NEW.column)
397      *   -- {tablename}_trigger_{optional_string}_before_update_{column_name}(OLD.column, NEW.column}
398      *   -- {tablename}_trigger_{optional_string}_before_insert_{column_name}(OLD.column}
399      *
400      *
401      */
402     // type = update/insert/delete
403     
404     function listTriggerFunctions($table, $type)
405     {
406         static $cache = array();
407         if (!isset($cache[$table])) {
408             $cache[$table] = array();
409             $q = DB_DAtaObject::factory('core_enum');
410             $q->query("SELECT
411                             SPECIFIC_NAME
412                         FROM
413                             information_schema.ROUTINES
414                         WHERE
415                             ROUTINE_SCHEMA = '{$q->escape($q->database())}'
416                             AND
417                             ROUTINE_NAME LIKE '" . $q->escape("{$table}_trigger_")  . "%'
418                             AND
419                             ROUTINE_TYPE = 'PROCEDURE'
420                             
421             ");
422             while ($q->fetch()) {
423                 $cache[$table][] = $q->SPECIFIC_NAME;
424             }
425             
426         }
427         // now see which of the procedures match the specification..
428         $ret = array();
429         foreach($cache[$table] as $cname) {
430             $bits = explode("_before_{$type}_", $cname);
431             if (count($bits) < 2) {
432                 continue;
433             }
434             $ret[$cname] = $bits[1];
435         }
436         return $ret;
437     }
438         
439     function updateCharacterSet()
440     {
441         foreach (array_keys($this->schema) as $tbl){
442             
443             if(strpos($tbl, '__keys') !== false ){
444                 continue;
445             }
446             
447             $ce = DB_DataObject::factory('core_enum');
448             
449             $ce->query("
450                 SELECT
451                         CCSA.character_set_name csname,
452                         CCSA.collation_name collatename
453                 FROM
454                         information_schema.`TABLES` T,
455                         information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
456                 WHERE
457                         CCSA.collation_name = T.table_collation
458                     AND
459                         T.table_schema = '{$ce->database()}' -- COLLATE utf8_unicode_ci
460                     AND
461                         T.table_name = '{$tbl}' -- COLLATE utf8_unicode_ci
462             ");
463                      
464             $ce->fetch();
465             
466             if($ce->csname == 'utf8' && $ce->collatename == 'utf8_unicode_ci'){
467                 echo "$tbl is Already utf8 \n";
468                 continue;
469             }
470             
471             $ce = DB_DataObject::factory('core_enum');
472             $ce->query("ALTER TABLE {$tbl} CONVERT TO CHARACTER SET  utf8 COLLATE utf8_unicode_ci");
473             echo "FIXED utf8 on {$tbl}\n";
474             
475         }
476     }
477     
478 }
479