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