e1cb545ecd117fc739240ed781d5a7155ddc86c4
[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/$m/UpdateDatabase.php";
201             if($m != 'Core' && file_exists($file)){
202                 
203                 require_once $file;
204                 $class = "Pman_{$m}_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         if (is_file($dir)) {
279             $files = array($dir);
280
281         } else {
282         
283         
284             $files = glob($dir.'/*.sql');
285             uksort($files, 'strcasecmp');
286         }
287         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
288         //usort($files, $lsort);
289         
290         
291         
292         foreach($files as $bfn) {
293
294
295             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
296                 continue;
297             }
298             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
299                 && !preg_match('#\.pg\.sql#i', basename($bfn))
300             ) { // skip migration scripts at present..
301                 continue;
302             }
303             $fn = false;
304
305             if (!preg_match('/pgsql/', basename($dir) )) {
306                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
307                     $fn = $this->convertToPG($bfn);
308                 }
309             }
310
311             // files ending in .pg.sql are native postgres files.. ## depricated
312
313
314             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
315
316             echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
317
318
319             passthru($cmd);
320
321             if ($fn) {
322                 unlink($fn);
323             }
324         }
325
326               
327              
328         
329     }
330     
331     
332     /**
333      * mysql - does not support conversions.
334      * 
335      *
336      */
337     
338     
339     function importmysqldir($dburl, $dir)
340     {
341         echo "Import MYSQL :: $dir\n";
342         
343         
344         require_once 'System.php';
345         $cat = System::which('cat');
346         $mysql = System::which('mysql');
347         
348        
349            
350         $mysql_cmd = $mysql .
351             ' -h ' . $dburl['host'] .
352             ' -u' . escapeshellarg($dburl['user']) .
353             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
354             ' ' . basename($dburl['path']);
355         //echo $mysql_cmd . "\n" ;
356         
357         $files = glob($dir.'/*.sql');
358         uksort($files, 'strcasecmp');
359         
360        
361         foreach($files as $fn) {
362                 
363                  
364                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
365                     continue;
366                 }
367                 // .my.sql but not .pg.sql
368                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
369                     && !preg_match('#\.my\.sql#i', basename($fn))
370                 ) { // skip migration scripts at present..
371                     continue;
372                 }
373                 if (!strlen(trim($fn))) {
374                     continue;
375                 }
376                 
377                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
378                 
379                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
380                 
381                 passthru($cmd);
382             
383                 
384         }
385        
386         
387         
388     }
389     
390     
391     /**
392      * simple regex based convert mysql to pgsql...
393      */
394     function convertToPG($src)
395     {
396         //echo "Convert $src\n";
397                
398         $fn = $this->tempName('sql');
399         
400         $ret = array( ); // pad it a bit.
401         $extra = array("", "" );
402         
403         $tbl = false;
404         foreach(file($src) as $l) {
405             $l = trim($l);
406             
407             if (!strlen($l) || $l[0] == '#') {
408                 continue;
409             }
410             $m = array();
411             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
412                 $tbl = $m[1];
413              }
414             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
415                 $tbl = 'shop_' . strtolower($m[1]);
416                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
417             }
418             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
419                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
420             }
421             // autoinc
422             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
423                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
424                 $extra[]  =   "create sequence {$tbl}_seq;";
425               
426             }
427             
428             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
429                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
430             }
431             
432             // enum value -- use the text instead..
433             
434             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
435                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
436             }
437             // ignore the alter enum
438             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
439                 continue;
440             }
441             
442             // UNIQUE KEY .. ignore
443             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
444                 $last = array_pop($ret);
445                 $ret[] = trim($last, ",");
446                 continue;
447             }
448             
449             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
450                 continue;
451             }
452             
453             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
454                 continue;
455             }
456             
457             // INDEX lookup ..ignore
458             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
459                $last = array_pop($ret);
460                $ret[] = trim($last, ",");
461                continue;
462                
463             }
464             
465             // CREATE INDEX ..ignore
466             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
467 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
468                 continue;
469              }
470              
471             // basic types..
472             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
473             
474             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
475             $l = preg_replace('# blob#i', ' TEXT', $l);
476             $l = preg_replace('# longtext#i', ' TEXT', $l);
477             $l = preg_replace('# tinyint#i', ' INT', $l);
478             
479             $ret[] = $l;
480             
481         }
482         
483         $ret = array_merge($extra,$ret);
484 //        echo implode("\n", $ret); exit;
485         
486         file_put_contents($fn, implode("\n", $ret));
487         
488         return $fn;
489     }
490     
491     
492     function checkOpts($opts)
493     {
494         
495         
496         foreach($opts as $o=>$v) {
497             if (!preg_match('/^json-/', $o) || empty($v)) {
498                 continue;
499             }
500             if (!file_exists($v)) {
501                 die("File does not exist : OPTION --{$o} = {$v} \n");
502             }
503         }
504         
505         $modules = array_reverse($this->modulesList());
506         
507         // move 'project' one to the end...
508         
509         foreach ($modules as $module){
510             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
511             if($module == 'Core' || !file_exists($file)){
512                 continue;
513             }
514             require_once $file;
515             $class = "Pman_{$module}_UpdateDatabase";
516             $x = new $class;
517             if(!method_exists($x, 'checkOpts')){
518                 continue;
519             };
520             $x->checkOpts($opts);
521         }
522                 
523     }
524     static function jsonImportFromArray($opts)
525     {
526         foreach($opts as $o=>$v) {
527             if (!preg_match('/^json-/', $o) || empty($v)) {
528                 continue;
529             }
530             $type = str_replace('_', '-', substr($o,5));
531             
532             $data= json_decode(file_get_contents($v),true);
533             $pg = HTML_FlexyFramework::get()->page;
534             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
535             
536         }
537         
538         
539         
540     }
541     
542     
543     
544     function runUpdateModulesData()
545     {
546         
547         
548         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
549         echo "Running jsonImportFromArray\n";
550         Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
551         
552         
553         echo "Running updateData on modules\n";
554         // runs core...
555         echo "Core\n";
556         $this->updateData(); 
557         $modules = array_reverse($this->modulesList());
558         
559         // move 'project' one to the end...
560         
561         foreach ($modules as $module){
562             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
563             if($module == 'Core' || !file_exists($file)){
564                 continue;
565             }
566             
567             require_once $file;
568             $class = "Pman_{$module}_UpdateDatabase";
569             $x = new $class;
570             if(!method_exists($x, 'updateData')){
571                 continue;
572             };
573             echo "$module\n";
574             $x->updateData();
575         }
576                 
577     }
578     
579     
580     function updateDataEnums()
581     {
582         
583         $enum = DB_DataObject::Factory('core_enum');
584         //DB_DAtaObject::debugLevel(1);
585         $enum->initEnums(
586             array(
587                 array(
588                     'etype' => '',
589                     'name' => 'COMPTYPE',
590                     'display_name' =>  'Company Types',
591                     'is_system_enum' => 1,
592                     'cn' => array(
593                         array(
594                             'name' => 'OWNER',
595                             'display_name' => 'Owner',
596                             'seqid' => 999, // last...
597                             'is_system_enum' => 1,
598                         )
599                         
600                     )
601                 ),
602                 array(
603                     'etype' => '',
604                     'name' => 'HtmlEditor.font-family',
605                     'display_name' =>  'HTML Editor font families',
606                     'is_system_enum' => 1,
607                     'cn' => array(
608                         array(
609                             'name' => 'Helvetica,Arial,sans-serif',
610                             'display_name' => 'Helvetica',
611                             
612                         ),
613                         
614                         array(
615                             'name' => 'Courier New',
616                             'display_name' => 'Courier',
617                              
618                         ),
619                         array(
620                             'name' => 'Tahoma',
621                             'display_name' => 'Tahoma',
622                             
623                         ),
624                         array(
625                             'name' => 'Times New Roman,serif',
626                             'display_name' => 'Times',
627                            
628                         ),
629                         array(
630                             'name' => 'Verdana',
631                             'display_name' => 'Verdana',
632                             
633                         ),
634                         
635                             
636                         
637                     )
638                 ),
639             )
640         ); 
641         
642     }
643     function updateDataGroups()
644     {
645          
646         $groups = DB_DataObject::factory('groups');
647         $groups->initGroups();
648         
649         $groups->initDatabase($this,array(
650             array(
651                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
652                 'type' => 0, // system
653             ),
654             array(
655                 'name' => 'system-email-from',
656                 'type' => 0, // system
657             ),
658         ));
659         
660     }
661     
662     function updateDataCompanies()
663     {
664          
665         // fix comptypes enums..
666         $c = DB_DataObject::Factory('Companies');
667         $c->selectAdd();
668         $c->selectAdd('distinct(comptype) as comptype');
669         $c->whereAdd("comptype != ''");
670         
671         $ctb = array();
672         foreach($c->fetchAll('comptype') as $cts) {
673             
674             
675             
676            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
677         
678         }
679          $c = DB_DataObject::Factory('core_enum');
680          
681         $c->initEnums($ctb);
682         //DB_DataObject::debugLevel(1);
683         // fix comptypeid
684         $c = DB_DataObject::Factory('Companies');
685         $c->query("
686             UPDATE Companies 
687                 SET
688                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
689                 WHERE
690                     comptype_id = 0
691                     AND
692                     LENGTH(comptype) > 0
693                   
694                   
695                   ");
696          
697         
698         
699     }
700     
701     function updateData()
702     {
703         // fill i18n data..
704         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
705         $this->updateDataEnums();
706         $this->updateDataGroups();
707         $this->updateDataCompanies();
708         
709         $c = DB_DataObject::Factory('I18n');
710         $c->buildDB();
711          
712        
713         
714         
715     }
716     
717     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
718     
719     function fixSequencesMysql()
720     {
721         // not required...
722     }
723     
724     function fixSequencesPgsql()
725     {
726      
727      
728         //DB_DataObject::debugLevel(1);
729         $cs = DB_DataObject::factory('core_enum');
730         $cs->query("
731          SELECT
732                     'ALTER SEQUENCE '||
733                     CASE WHEN strpos(seq_name, '.') > 0 THEN
734                         min(seq_name)
735                     ELSE 
736                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
737                     END 
738                     
739                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
740                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
741              FROM (
742                       
743                        SELECT 
744                      n.nspname AS schema_name,
745                      c.relname AS table_name,
746                      a.attname AS column_name, 
747                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
748                  FROM pg_class c 
749                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
750                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
751                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
752                  WHERE has_schema_privilege(n.oid,'USAGE')
753                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
754                    AND has_table_privilege(c.oid,'SELECT')
755                    AND (NOT a.attisdropped)
756                    AND d.adsrc ~ '^nextval'
757               
758              ) seq
759              WHERE
760                  CASE WHEN strpos(seq_name, '.') > 0 THEN
761                      substring(seq_name, 1,strpos(seq_name,'.')-1)
762                 ELSE
763                     schema_name
764                 END = schema_name
765              
766              GROUP BY seq_name HAVING count(*)=1
767              ");
768         $cmds = array();
769         while ($cs->fetch()) {
770             $cmds[] = $cs->cmd;
771         }
772         foreach($cmds as $cmd) {
773             $cs = DB_DataObject::factory('core_enum');
774             echo "$cmd\n";
775             $cs->query($cmd);
776         }
777         $cs = DB_DataObject::factory('core_enum');
778          $cs->query("
779                SELECT  'SELECT SETVAL(' ||
780                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
781                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
782                 FROM pg_class AS S,
783                     pg_depend AS D,
784                     pg_class AS T,
785                     pg_attribute AS C,
786                     pg_namespace AS NS
787                 WHERE S.relkind = 'S'
788                     AND S.oid = D.objid
789                     AND D.refobjid = T.oid
790                     AND D.refobjid = C.attrelid
791                     AND D.refobjsubid = C.attnum
792                     AND NS.oid = T.relnamespace
793                 ORDER BY S.relname   
794         ");
795          $cmds = array();
796         while ($cs->fetch()) {
797             $cmds[] = $cs->cmd;
798         }
799         foreach($cmds as $cmd) {
800             $cs = DB_DataObject::factory('core_enum');
801             echo "$cmd\n";
802             $cs->query($cmd);
803         }
804        
805     }
806     
807 }