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