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