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