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