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