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