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