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