UpdateDatabase.php
[Pman.Core] / UpdateDatabase.php
1 <?php
2
3 /**
4  *
5  * This applies database files from
6  * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
7  *
8  * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9  *  and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
10  *
11  *
12  */
13
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
16 {
17     
18     static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
19  
20     static $cli_opts = array(
21       
22         'prefix' => array(
23             'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
24             'short' => 'p',
25             'default' => '',
26             'min' => 1,
27             'max' => 1,
28         ),
29         'add-company' => array(
30             'desc' => 'add a company name of the company',
31             'short' => 'n',
32             'default' => '',
33             'min' => 1,
34             'max' => 1,
35         ),
36         'add-company-with-type' => array(
37             'desc' => 'the type of company (default OWNER)',
38             'short' => 't',
39             'default' => '',
40             'min' => 1,
41             'max' => 1,
42         ),
43         'init' => array(
44             'desc' => 'Initialize the database (pg only supported)',
45             'short' => 'i',
46             'default' => '',
47             'min' => 1,
48             'max' => 1,
49         ),
50         'only-module-sql' => array(
51             'desc' => 'Only run sql import on this modules - eg. Core',
52             'default' => '',
53             'min' => 1,
54             'max' => 1,
55         ),
56         
57         'json-person' => array(
58             'desc' => 'Person JSON file',
59             'default' => '',
60             'min' => 1,
61             'max' => 1,
62             
63         ),
64     );
65     
66     static function cli_opts()
67     {
68         
69         $ret = self::$cli_opts;
70         $ff = HTML_FlexyFramework::get();
71         $a = new Pman();
72         $mods = $a->modulesList();
73         foreach($mods as $m) {
74             
75             $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
76             if (!file_exists($fd)) {
77                 continue;
78             }
79             
80             require_once $fd;
81             
82             $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
83             
84             $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
85             
86             
87         }
88         
89         return $ret;
90     }
91     
92     var $opts = false;
93     
94     
95     var $cli = false;
96     function getAuth() {
97         
98         
99         $ff = HTML_FlexyFramework::get();
100         if (!empty($ff->cli)) {
101             $this->cli = true;
102             return true;
103         }
104         
105         parent::getAuth(); // load company!
106         $au = $this->getAuthUser();
107         if (!$au || $au->company()->comptype != 'OWNER') {
108             $this->jerr("Not authenticated", array('authFailure' => true));
109         }
110         $this->authUser = $au;
111         return true;
112     }
113      
114     function get($args, $opts)
115     {
116         //$this->fixSequencesPgsql();exit;
117         $this->opts = $opts;
118         
119         // ask all the modules to verify the opts
120         
121         $this->checkOpts($opts);
122         
123         
124         if (!empty($opts['add-company'])) {
125             DB_DataObject::factory('companies')->initCompanies($this, $opts);
126         }
127         
128         
129         $this->importSQL();
130         if (!empty($opts['only-module-sql'])) {
131             return;
132         }
133         
134         $this->runUpdateModulesData();
135          
136     }
137     function output() {
138         return '';
139     }
140      /**
141      * imports SQL files from all DataObjects directories....
142      * 
143      * except any matching /migrate/
144      */
145     function importSQL()
146     {
147         
148         $ff = HTML_Flexyframework::get();
149         
150         $url = parse_url($ff->DB_DataObject['database']);
151         
152         $this->{'import' . $url['scheme']}($url);
153         
154     }
155     
156     /**
157      * mysql - does not support conversions.
158      * 
159      *
160      */
161     
162     
163     function importmysqldir($dburl, $dir)
164     {
165         echo "Import MYSQL :: $dir\n";
166         
167         
168         require_once 'System.php';
169         $cat = System::which('cat');
170         $mysql = System::which('mysql');
171         
172        
173            
174         $mysql_cmd = $mysql .
175             ' -h ' . $dburl['host'] .
176             ' -u' . escapeshellarg($dburl['user']) .
177             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
178             ' ' . basename($dburl['path']);
179         //echo $mysql_cmd . "\n" ;
180        
181        
182         foreach(glob($dir.'/*.sql') as $fn) {
183                 
184                  
185                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
186                     continue;
187                 }
188                 // .my.sql but not .pg.sql
189                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
190                     && !preg_match('#\.my\.sql#i', basename($fn))
191                 ) { // skip migration scripts at present..
192                     continue;
193                 }
194                 if (!strlen(trim($fn))) {
195                     continue;
196                 }
197                 
198                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
199                 
200                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
201                 
202                 passthru($cmd);
203             
204                 
205         }
206        
207         
208         
209     }
210     
211     
212     
213     function importmysql($dburl)
214     {
215         
216         // hide stuff for web..
217         $ar = $this->modulesList();
218         
219          
220         
221         // old -- DAtaObjects/*.sql
222         
223         foreach($ar as $m) {
224             
225             if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
226                 continue;
227             }
228             
229             $fd = $this->rootDir. "/Pman/$m/DataObjects";
230             
231             $this->importmysqldir($dburl, $fd);
232             
233             // new -- sql directory..
234             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
235             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
236             
237             $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
238             $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
239               
240             
241         }
242         
243         
244         
245     }
246     /**
247      * postgresql import..
248      */
249     function importpgsql($dburl)
250     {
251         
252         // hide stuff for web..
253         
254         
255        
256         
257         $ar = $this->modulesList();
258        
259         print_R($ar);
260         foreach($ar as $m) {
261              echo "Importing SQL from module $m\n";
262             if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
263                 continue;
264             }
265             echo "Importing SQL from module $m\n";
266             // if init has been called
267             // look in pgsql.ini
268             if (!empty($this->opts['init'])) {
269                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
270                 
271             }
272             
273             
274             
275             $fd = $this->rootDir. "/Pman/$m/DataObjects";
276             
277             $this->importpgsqldir($dburl, $fd);
278             
279             // new -- sql directory..
280             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
281             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
282             
283             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
284             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
285             
286             
287             
288             if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
289                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
290                 
291                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
292                 $this->fixSequencesPgsql();
293                 
294             }
295               
296             
297         }
298        
299           
300     }
301     function importpgsqldir($url, $dir, $disable_triggers = false)
302     {
303         require_once 'System.php';
304         $cat = System::which('cat');
305         $psql = System::which('psql');
306         
307          
308         if (!empty($url['pass'])) { 
309             putenv("PGPASSWORD=". $url['pass']);
310         }
311            
312         $psql_cmd = $psql .
313             ' -h ' . $url['host'] .
314             ' -U' . escapeshellarg($url['user']) .
315              ' ' . basename($url['path']);
316         
317         
318         echo $psql_cmd . "\n" ;
319         echo "scan : $dir\n";
320         foreach(glob($dir.'/*.sql') as $bfn) {
321
322
323             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
324                 continue;
325             }
326             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
327                 && !preg_match('#\.pg\.sql#i', basename($bfn))
328             ) { // skip migration scripts at present..
329                 continue;
330             }
331             $fn = false;
332
333             if (!preg_match('/pgsql/', basename($dir) )) {
334                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
335                     $fn = $this->convertToPG($bfn);
336                 }
337             }
338
339             // files ending in .pg.sql are native postgres files.. ## depricated
340
341
342             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
343
344             echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
345
346
347             passthru($cmd);
348
349             if ($fn) {
350                 unlink($fn);
351             }
352         }
353
354               
355              
356         
357     }
358     /**
359      * simple regex based convert mysql to pgsql...
360      */
361     function convertToPG($src)
362     {
363         //echo "Convert $src\n";
364                
365         $fn = $this->tempName('sql');
366         
367         $ret = array( ); // pad it a bit.
368         $extra = array("", "" );
369         
370         $tbl = false;
371         foreach(file($src) as $l) {
372             $l = trim($l);
373             
374             if (!strlen($l) || $l[0] == '#') {
375                 continue;
376             }
377             $m = array();
378             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
379                 $tbl = $m[1];
380              }
381             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
382                 $tbl = 'shop_' . strtolower($m[1]);
383                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
384             }
385             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
386                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
387             }
388             // autoinc
389             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
390                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
391                 $extra[]  =   "create sequence {$tbl}_seq;";
392               
393             }
394             
395             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
396                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
397             }
398             
399             // enum value -- use the text instead..
400             
401             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
402                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
403             }
404             // ignore the alter enum
405             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
406                 continue;
407             }
408             
409             // UNIQUE KEY .. ignore
410             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
411                 $last = array_pop($ret);
412                 $ret[] = trim($last, ",");
413                 continue;
414             }
415             
416             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
417                 continue;
418             }
419             
420             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
421                 continue;
422             }
423             
424             // INDEX lookup ..ignore
425             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
426                $last = array_pop($ret);
427                $ret[] = trim($last, ",");
428                continue;
429                
430             }
431             
432             // CREATE INDEX ..ignore
433             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
434 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
435                 continue;
436              }
437              
438             // basic types..
439             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
440             
441             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
442             $l = preg_replace('# blob#i', ' TEXT', $l);
443             $l = preg_replace('# longtext#i', ' TEXT', $l);
444             $l = preg_replace('# tinyint#i', ' INT', $l);
445             
446             $ret[] = $l;
447             
448         }
449         
450         $ret = array_merge($extra,$ret);
451 //        echo implode("\n", $ret); exit;
452         
453         file_put_contents($fn, implode("\n", $ret));
454         
455         return $fn;
456     }
457     
458     
459     function checkOpts($opts)
460     {
461         
462         
463         foreach($opts as $o=>$v) {
464             if (!preg_match('/^json-/', $o) || empty($v)) {
465                 continue;
466             }
467             if (!file_exists($v)) {
468                 die("File does not exist : OPTION --{$o} = {$v} \n");
469             }
470         }
471         
472         $modules = array_reverse($this->modulesList());
473         
474         // move 'project' one to the end...
475         
476         foreach ($modules as $module){
477             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
478             if($module == 'Core' || !file_exists($file)){
479                 continue;
480             }
481             require_once $file;
482             $class = "Pman_{$module}_UpdateDatabase";
483             $x = new $class;
484             if(!method_exists($x, 'checkOpts')){
485                 continue;
486             };
487             $x->checkOpts($opts);
488         }
489                 
490     }
491     static function jsonImportFromArray($opts)
492     {
493         foreach($opts as $o=>$v) {
494             if (!preg_match('/^json-/', $o) || empty($v)) {
495                 continue;
496             }
497             $type = str_replace('_', '-', substr($o,6));
498             $data= json_decode(file_get_contents($file),true);
499             DB_DataObject::factory($type)->importFromArray($this,$data,$opts);
500             
501         }
502         
503         
504         
505     }
506     
507     function runUpdateModulesData()
508     {
509         
510         
511         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
512         echo "Running jsonImportFromArray\n";
513         Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
514         
515         
516         echo "Running updateData on modules\n";
517         // runs core...
518         echo "Core\n";
519         $this->updateData(); 
520         $modules = array_reverse($this->modulesList());
521         
522         // move 'project' one to the end...
523         
524         foreach ($modules as $module){
525             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
526             if($module == 'Core' || !file_exists($file)){
527                 continue;
528             }
529             
530             require_once $file;
531             $class = "Pman_{$module}_UpdateDatabase";
532             $x = new $class;
533             if(!method_exists($x, 'updateData')){
534                 continue;
535             };
536             echo "$module\n";
537             $x->updateData();
538         }
539                 
540     }
541     
542     
543     function updateDataEnums()
544     {
545         $enum = DB_DataObject::Factory('core_enum');
546         $enum->initEnums(
547             array(
548                 array(
549                     'etype' => '',
550                     'name' => 'COMPTYPE',
551                     'display_name' =>  'Company Types',
552                     'is_system_enum' => 1,
553                     'cn' => array(
554                         array(
555                             'name' => 'OWNER',
556                             'display_name' => 'Owner',
557                             'seqid' => 999, // last...
558                             'is_system_enum' => 1,
559                         )
560                         
561                     )
562                 ),
563                 array(
564                     'etype' => '',
565                     'name' => 'HtmlEditor.font-family',
566                     'display_name' =>  'HTML Editor font families',
567                     'is_system_enum' => 1,
568                     'cn' => array(
569                         array(
570                             'name' => 'Helvetica,Arial,sans-serif',
571                             'display_name' => 'Helvetica',
572                             
573                         ),
574                         
575                         array(
576                             'name' => 'Courier New',
577                             'display_name' => 'Courier',
578                              
579                         ),
580                         array(
581                             'name' => 'Tahoma',
582                             'display_name' => 'Tahoma',
583                             
584                         ),
585                         array(
586                             'name' => 'Times New Roman,serif',
587                             'display_name' => 'Times',
588                            
589                         ),
590                         array(
591                             'name' => 'Verdana',
592                             'display_name' => 'Verdana',
593                             
594                         ),
595                         
596                             
597                         
598                     )
599                 ),
600             )
601         ); 
602         
603     }
604     function updateDataGroups()
605     {
606          
607         $groups = DB_DataObject::factory('groups');
608         $groups->initGroups();
609         
610         $groups->initDatabase($this,array(
611             array(
612                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
613                 'type' => 0, // system
614             ),
615             
616         ));
617         
618     }
619     
620     function updateDataCompanies()
621     {
622          
623         // fix comptypes enums..
624         $c = DB_DataObject::Factory('Companies');
625         $c->selectAdd();
626         $c->selectAdd('distinct(comptype) as comptype');
627         $c->whereAdd("comptype != ''");
628         
629         $ctb = array();
630         foreach($c->fetchAll('comptype') as $cts) {
631             
632             
633             
634            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
635         
636         }
637          $c = DB_DataObject::Factory('core_enum');
638          
639         $c->initEnums($ctb);
640         //DB_DataObject::debugLevel(1);
641         // fix comptypeid
642         $c = DB_DataObject::Factory('Companies');
643         $c->query("
644             UPDATE Companies 
645                 SET
646                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
647                 WHERE
648                     comptype_id = 0
649                     AND
650                     LENGTH(comptype) > 0
651                   
652                   
653                   ");
654          
655         
656         
657     }
658     
659     function updateData()
660     {
661         // fill i18n data..
662         
663         $this->updateDataEnums();
664         $this->updateDataGroups();
665         $this->updateDataCompanies();
666         
667         $c = DB_DataObject::Factory('I18n');
668         $c->buildDB();
669          
670        
671         
672         
673     }
674     function fixSequencesPgsql()
675     {
676         //DB_DataObject::debugLevel(1);
677         $cs = DB_DataObject::factory('core_enum');
678         $cs->query("
679          SELECT 'ALTER SEQUENCE '|| quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
680                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
681                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
682              FROM (
683                       
684                        SELECT 
685                      n.nspname AS schema_name,
686                      c.relname AS table_name,
687                      a.attname AS column_name, 
688                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\"]*', ''),E'[''\"]*::.*\$','') AS seq_name 
689                  FROM pg_class c 
690                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
691                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
692                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
693                  WHERE has_schema_privilege(n.oid,'USAGE')
694                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
695                    AND has_table_privilege(c.oid,'SELECT')
696                    AND (NOT a.attisdropped)
697                    AND d.adsrc ~ '^nextval'
698               
699              ) seq
700              GROUP BY seq_name HAVING count(*)=1
701              ");
702         $cmds = array();
703         while ($cs->fetch()) {
704             $cmds[] = $cs->cmd;
705         }
706         foreach($cmds as $cmd) {
707             $cs = DB_DataObject::factory('core_enum');
708             $cs->query($cmd);
709         }
710         $cs = DB_DataObject::factory('core_enum');
711          $cs->query("
712                SELECT  'SELECT SETVAL(' ||
713                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
714                         ', MAX(' || quote_ident(C.attname)|| ') )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
715                 FROM pg_class AS S,
716                     pg_depend AS D,
717                     pg_class AS T,
718                     pg_attribute AS C,
719                     pg_namespace AS NS
720                 WHERE S.relkind = 'S'
721                     AND S.oid = D.objid
722                     AND D.refobjid = T.oid
723                     AND D.refobjid = C.attrelid
724                     AND D.refobjsubid = C.attnum
725                     AND NS.oid = T.relnamespace
726                 ORDER BY S.relname;     
727         ");
728          $cmds = array();
729         while ($cs->fetch()) {
730             $cmds[] = $cs->cmd;
731         }
732         foreach($cmds as $cmd) {
733             $cs = DB_DataObject::factory('core_enum');
734             $cs->query($cmd);
735         }
736        
737     }
738     
739 }