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