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