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