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