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