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