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