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         '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     var $disabled = array();
109     
110     
111     var $cli = false;
112     function getAuth() {
113         
114         
115         $ff = HTML_FlexyFramework::get();
116         if (!empty($ff->cli)) {
117             $this->cli = true;
118             return true;
119         }
120         
121         parent::getAuth(); // load company!
122         $au = $this->getAuthUser();
123         if (!$au || $au->company()->comptype != 'OWNER') {
124             $this->jerr("Not authenticated", array('authFailure' => true));
125         }
126         $this->authUser = $au;
127         return true;
128     }
129      
130     function get($args, $opts)
131     {
132         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
133    
134         $this->checkSystem();
135    
136         $ff = HTML_FlexyFramework::get();
137         
138         if(!empty($ff->Core_Notify)){
139             print_R($ff->Core_Notify);
140         }
141         exit;
142         $this->disabled = explode(',', $ff->disable);
143         
144         //$this->fixSequencesPgsql();exit;
145         $this->opts = $opts;
146         
147         // ask all the modules to verify the opts
148         
149         $this->checkOpts($opts);
150         
151         if (empty($opts['data-only'])) {
152             $this->importSQL();
153         }
154         if (!empty($opts['only-module-sql'])) {
155             return;
156         }
157         
158         $this->runUpdateModulesData();
159         
160         
161         if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
162             // make sure we have a good cache...?
163            
164             DB_DataObject::factory('companies')->initCompanies($this, $opts);
165         }
166         
167         $this->runExtensions();
168          
169          
170     }
171     function output() {
172         return '';
173     }
174      /**
175      * imports SQL files from all DataObjects directories....
176      * 
177      * except any matching /migrate/
178      */
179     function importSQL()
180     {
181         
182         // loop through all the modules, and see if they have a importSQL method?
183         
184         
185         $ff = HTML_Flexyframework::get();
186         
187         $dburl = parse_url($ff->DB_DataObject['database']);
188         
189         //$this->{'import' . $url['scheme']}($url);
190         
191         $dbtype = $dburl['scheme'];
192         $dirmethod = 'import' . $dburl['scheme'] . 'dir';
193         
194         
195        
196         
197         $ar = $this->modulesList();
198         
199         foreach($ar as $m) {
200             
201             if(in_array($m, $this->disabled)){
202                 echo "module $m is disabled \n";
203                 continue;
204             }
205             
206             echo "Importing SQL from module $m\n";
207             if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
208                 continue;
209             }
210             
211             
212             // check to see if the class has
213             
214             
215             
216             $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
217             if($m != 'Core' && file_exists($file)){
218                 
219                 require_once $file;
220                 $class = "Pman_{$m}_UpdateDatabase";
221                 $x = new $class;
222                 if(method_exists($x, 'importModuleSQL')){
223                     echo "Importing SQL from module $m using Module::importModuleSQL\n";
224                     $x->opts = $this->opts;
225                     $x->rootDir = $this->rootDir;
226                     $x->importModuleSQL($dburl);
227                     continue;
228                 }
229             };
230
231             echo "Importing SQL from module $m\n";
232             
233             
234             // if init has been called
235             // look in pgsql.ini
236             if (!empty($this->opts['init'])) {
237                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
238                 
239             }
240             
241             
242             
243             $fd = $this->rootDir. "/Pman/$m/DataObjects";
244             
245             $this->{$dirmethod}($dburl, $fd);
246             
247             
248             // new -- sql directory..
249             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
250             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
251             
252             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
253             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
254             
255             
256             
257             if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
258                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
259                 
260                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
261                 $this->{'fixSequences'. $dbtype}();
262                 
263             }
264               
265             
266         }
267         
268     }
269     
270     
271     
272      
273     /** -------------- code to handle importing a whole directory of files into the database  -------  **/
274     
275     
276     function importpgsqldir($url, $dir, $disable_triggers = false)
277     {
278         $ff = HTML_FlexyFramework::get();
279         
280         require_once 'System.php';
281         $cat = System::which('cat');
282         $psql = System::which('psql');
283         
284          
285         if (!empty($url['pass'])) { 
286             putenv("PGPASSWORD=". $url['pass']);
287         }
288            
289         $psql_cmd = $psql .
290             ' -h ' . $url['host'] .
291             ' -U' . escapeshellarg($url['user']) .
292              ' ' . basename($url['path']);
293         
294         
295         echo $psql_cmd . "\n" ;
296         echo "scan : $dir\n";
297         
298         if (is_file($dir)) {
299             $files = array($dir);
300
301         } else {
302         
303         
304             $files = glob($dir.'/*.sql');
305             uksort($files, 'strcasecmp');
306         }
307         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
308         //usort($files, $lsort);
309         
310         
311         foreach($files as $bfn) {
312
313
314             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
315                 continue;
316             }
317             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
318                 && !preg_match('#\.pg\.sql#i', basename($bfn))
319             ) { // skip migration scripts at present..
320                 continue;
321             }
322             $fn = false;
323
324             if (!preg_match('/pgsql/', basename($dir) )) {
325                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
326                     $fn = $this->convertToPG($bfn);
327                 }
328             }
329
330             // files ending in .pg.sql are native postgres files.. ## depricated
331
332
333             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
334
335             echo "$bfn:   $cmd ". ($ff->cli ? "\n" : "<BR>\n");
336
337             passthru($cmd);
338
339             if ($fn) {
340                 unlink($fn);
341             }
342         }
343
344               
345              
346         
347     }
348     
349     
350     /**
351      * mysql - does not support conversions.
352      * 
353      *
354      */
355     
356     
357     function importmysqldir($dburl, $dir)
358     {
359         
360         $this->fixMysqlInnodb(); /// run once 
361         
362         echo "Import MYSQL :: $dir\n";
363         
364         
365         require_once 'System.php';
366         $cat = System::which('cat');
367         $mysql = System::which('mysql');
368         
369        
370            
371         $mysql_cmd = $mysql .
372             ' -h ' . $dburl['host'] .
373             ' -u' . escapeshellarg($dburl['user']) .
374             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
375             ' ' . basename($dburl['path']);
376         //echo $mysql_cmd . "\n" ;
377         
378         $files = glob($dir.'/*.sql');
379         uksort($files, 'strcasecmp');
380         
381        
382         foreach($files as $fn) {
383                 
384                  
385                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
386                     continue;
387                 }
388                 // .my.sql but not .pg.sql
389                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
390                     && !preg_match('#\.my\.sql#i', basename($fn))
391                 ) { // skip migration scripts at present..
392                     continue;
393                 }
394                 if (!strlen(trim($fn))) {
395                     continue;
396                 }
397                 
398                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
399                 
400                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
401                 
402                 passthru($cmd);
403             
404                 
405         }
406        
407         
408         
409     }
410     
411     
412     /**
413      * simple regex based convert mysql to pgsql...
414      */
415     function convertToPG($src)
416     {
417         //echo "Convert $src\n";
418                
419         $fn = $this->tempName('sql');
420         
421         $ret = array( ); // pad it a bit.
422         $extra = array("", "" );
423         
424         $tbl = false;
425         foreach(file($src) as $l) {
426             $l = trim($l);
427             
428             if (!strlen($l) || $l[0] == '#') {
429                 continue;
430             }
431             $m = array();
432             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
433                 $tbl = $m[1];
434              }
435             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
436                 $tbl = 'shop_' . strtolower($m[1]);
437                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
438             }
439             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
440                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
441             }
442             // autoinc
443             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
444                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
445                 $extra[]  =   "create sequence {$tbl}_seq;";
446               
447             }
448             
449             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
450                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
451             }
452             
453             // enum value -- use the text instead..
454             
455             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
456                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
457             }
458             // ignore the alter enum
459             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
460                 continue;
461             }
462             
463             // UNIQUE KEY .. ignore
464             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
465                 $last = array_pop($ret);
466                 $ret[] = trim($last, ",");
467                 continue;
468             }
469             
470             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
471                 continue;
472             }
473             
474             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
475                 continue;
476             }
477             
478             // INDEX lookup ..ignore
479             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
480                $last = array_pop($ret);
481                $ret[] = trim($last, ",");
482                continue;
483                
484             }
485             
486             // CREATE INDEX ..ignore
487             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
488 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
489                 continue;
490              }
491              
492             // basic types..
493             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
494             
495             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
496             $l = preg_replace('# blob#i', ' TEXT', $l);
497             $l = preg_replace('# longtext#i', ' TEXT', $l);
498             $l = preg_replace('# tinyint#i', ' INT', $l);
499             
500             $ret[] = $l;
501             
502         }
503         
504         $ret = array_merge($extra,$ret);
505 //        echo implode("\n", $ret); exit;
506         
507         file_put_contents($fn, implode("\n", $ret));
508         
509         return $fn;
510     }
511     
512     
513     function checkOpts($opts)
514     {
515         
516         
517         foreach($opts as $o=>$v) {
518             if (!preg_match('/^json-/', $o) || empty($v)) {
519                 continue;
520             }
521             if (!file_exists($v)) {
522                 die("File does not exist : OPTION --{$o} = {$v} \n");
523             }
524         }
525         
526         $modules = array_reverse($this->modulesList());
527         
528         // move 'project' one to the end...
529         
530         foreach ($modules as $module){
531             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
532             if($module == 'Core' || !file_exists($file)){
533                 continue;
534             }
535             require_once $file;
536             $class = "Pman_{$module}_UpdateDatabase";
537             $x = new $class;
538             if(!method_exists($x, 'checkOpts')){
539                 continue;
540             };
541             $x->checkOpts($opts);
542         }
543                 
544     }
545     static function jsonImportFromArray($opts)
546     {
547         foreach($opts as $o=>$v) {
548             if (!preg_match('/^json-/', $o) || empty($v)) {
549                 continue;
550             }
551             $type = str_replace('_', '-', substr($o,5));
552             
553             $data= json_decode(file_get_contents($v),true);
554             $pg = HTML_FlexyFramework::get()->page;
555             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
556             
557         }
558         
559         
560         
561     }
562     
563     
564     
565     function runUpdateModulesData()
566     {
567         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
568         
569         if(!in_array('Core', $this->disabled)){
570             echo "Running jsonImportFromArray\n";
571             Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
572
573
574             echo "Running updateData on modules\n";
575             // runs core...
576             echo "Core\n";
577             $this->updateData(); 
578         }
579         
580         $modules = array_reverse($this->modulesList());
581         
582         // move 'project' one to the end...
583         
584         foreach ($modules as $module){
585             if(in_array($module, $this->disabled)){
586                 continue;
587             }
588             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
589             if($module == 'Core' || !file_exists($file)){
590                 continue;
591             }
592             
593             require_once $file;
594             $class = "Pman_{$module}_UpdateDatabase";
595             $x = new $class;
596             if(!method_exists($x, 'updateData')){
597                 continue;
598             };
599             echo "$module\n";
600             $x->updateData();
601         }
602                 
603     }
604     
605     
606     function updateDataEnums()
607     {
608         
609         $enum = DB_DataObject::Factory('core_enum');
610         //DB_DAtaObject::debugLevel(1);
611         $enum->initEnums(
612             array(
613                 array(
614                     'etype' => '',
615                     'name' => 'COMPTYPE',
616                     'display_name' =>  'Company Types',
617                     'is_system_enum' => 1,
618                     'cn' => array(
619                         array(
620                             'name' => 'OWNER',
621                             'display_name' => 'Owner',
622                             'seqid' => 999, // last...
623                             'is_system_enum' => 1,
624                         )
625                         
626                     )
627                 ),
628                 array(
629                     'etype' => '',
630                     'name' => 'HtmlEditor.font-family',
631                     'display_name' =>  'HTML Editor font families',
632                     'is_system_enum' => 1,
633                     'cn' => array(
634                         array(
635                             'name' => 'Helvetica,Arial,sans-serif',
636                             'display_name' => 'Helvetica',
637                             
638                         ),
639                         
640                         array(
641                             'name' => 'Courier New',
642                             'display_name' => 'Courier',
643                              
644                         ),
645                         array(
646                             'name' => 'Tahoma',
647                             'display_name' => 'Tahoma',
648                             
649                         ),
650                         array(
651                             'name' => 'Times New Roman,serif',
652                             'display_name' => 'Times',
653                            
654                         ),
655                         array(
656                             'name' => 'Verdana',
657                             'display_name' => 'Verdana',
658                             
659                         ),
660                         
661                             
662                         
663                     )
664                 ),
665             )
666         ); 
667         
668     }
669     function updateDataGroups()
670     {
671          
672         $groups = DB_DataObject::factory('groups');
673         $groups->initGroups();
674         
675         $groups->initDatabase($this,array(
676             array(
677                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
678                 'type' => 0, // system
679             ),
680             array(
681                 'name' => 'system-email-from',
682                 'type' => 0, // system
683             ),
684             array(
685                 'name' => 'core-person-signup-bcc',
686                 'type' => 0, // system
687             ),
688         ));
689         
690     }
691     
692     function updateDataCompanies()
693     {
694          
695         // fix comptypes enums..
696         $c = DB_DataObject::Factory('Companies');
697         $c->selectAdd();
698         $c->selectAdd('distinct(comptype) as comptype');
699         $c->whereAdd("comptype != ''");
700         
701         $ctb = array();
702         foreach($c->fetchAll('comptype') as $cts) {
703             
704             
705             
706            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
707         
708         }
709          $c = DB_DataObject::Factory('core_enum');
710          
711         $c->initEnums($ctb);
712         //DB_DataObject::debugLevel(1);
713         // fix comptypeid
714         $c = DB_DataObject::Factory('Companies');
715         $c->query("
716             UPDATE Companies 
717                 SET
718                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
719                 WHERE
720                     comptype_id = 0
721                     AND
722                     LENGTH(comptype) > 0
723                   
724                   
725                   ");
726          
727         
728         
729     }
730     
731     
732     function initEmails($templateDir, $emails)
733     {
734       
735         $pg = HTML_FlexyFramework::get()->page;
736         foreach($emails as $name=>$data) {
737             $cm = DB_DataObject::factory('core_email');
738             $update = $cm->get('name', $name);
739             $old = clone($cm);
740             
741             if (empty($cm->bcc_group)) {
742                 if (empty($data['bcc_group'])) {
743                     $this->jerr("missing bcc_group for template $name");
744                 }
745                 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
746                 
747                 if (!$g) {
748                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
749                 }
750                 if (!$g->members('email')) {
751                       $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
752                 }
753                 
754                 
755                 $cm->bcc_group = $g->id;
756             }
757             if (empty($cm->test_class)) {
758                 if (empty($data['test_class'])) {
759                     $this->jerr("missing test_class for template $name");
760                 }
761                 $cm->test_class = $data['test_class'];
762             }
763             require_once $cm->test_class . '.php';
764             
765             $clsname = str_replace('/','_', $cm->test_class);
766             try {
767                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
768                 $got_it = $method->isStatic();
769             } catch(Exception $e) {
770                 $got_it = false;
771                 
772             }
773             if (!$got_it) {
774                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
775             }
776             if ($update) {
777                 $cm->update($old);
778                 echo "email: {$name} - checked\n";
779                 continue; /// we do not import the body content of templates that exist...
780             } else {
781                 $cm->insert();
782             }
783             
784             
785     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
786             
787             $opts = array(
788                 'update' => 1,
789                 'file' => $templateDir. $name .'.html'
790             );
791             
792             if (!empty($data['master'])) {
793                 $opts['master'] = $templateDir . $master .'.html';
794             }
795             require_once 'Pman/Core/Import/Core_email.php';
796             $x = new Pman_Core_Import_Core_email();
797             $x->get('', $opts);
798             
799             echo "email: {$name} - CREATED\n";
800         }
801     }
802     
803     
804     function updateData()
805     {
806         // fill i18n data..
807         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
808         $this->updateDataEnums();
809         $this->updateDataGroups();
810         $this->updateDataCompanies();
811         
812         $c = DB_DataObject::Factory('I18n');
813         $c->buildDB();
814          
815        
816         
817         
818     }
819     
820     function fixMysqlInnodb()
821     {
822         
823         static $done_check = false;
824         if ($done_check) {
825             return;
826         }
827         // innodb in single files is far more efficient that MYD or one big innodb file.
828         // first check if database is using this format.
829         $db = DB_DataObject::factory('core_enum');
830         $db->query("show variables like 'innodb_file_per_table'");
831         $db->fetch();
832         if ($db->Value == 'OFF') {
833             die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
834         }
835         
836         $done_check = true;;
837
838  
839         
840         
841         
842         
843         
844     }
845     
846     
847     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
848     
849     function fixSequencesMysql()
850     {
851         // not required...
852     }
853     
854     function fixSequencesPgsql()
855     {
856      
857      
858         //DB_DataObject::debugLevel(1);
859         $cs = DB_DataObject::factory('core_enum');
860         $cs->query("
861          SELECT
862                     'ALTER SEQUENCE '||
863                     CASE WHEN strpos(seq_name, '.') > 0 THEN
864                         min(seq_name)
865                     ELSE 
866                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
867                     END 
868                     
869                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
870                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
871              FROM (
872                       
873                        SELECT 
874                      n.nspname AS schema_name,
875                      c.relname AS table_name,
876                      a.attname AS column_name, 
877                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
878                  FROM pg_class c 
879                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
880                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
881                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
882                  WHERE has_schema_privilege(n.oid,'USAGE')
883                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
884                    AND has_table_privilege(c.oid,'SELECT')
885                    AND (NOT a.attisdropped)
886                    AND d.adsrc ~ '^nextval'
887               
888              ) seq
889              WHERE
890                  CASE WHEN strpos(seq_name, '.') > 0 THEN
891                      substring(seq_name, 1,strpos(seq_name,'.')-1)
892                 ELSE
893                     schema_name
894                 END = schema_name
895              
896              GROUP BY seq_name HAVING count(*)=1
897              ");
898         $cmds = array();
899         while ($cs->fetch()) {
900             $cmds[] = $cs->cmd;
901         }
902         foreach($cmds as $cmd) {
903             $cs = DB_DataObject::factory('core_enum');
904             echo "$cmd\n";
905             $cs->query($cmd);
906         }
907         $cs = DB_DataObject::factory('core_enum');
908          $cs->query("
909                SELECT  'SELECT SETVAL(' ||
910                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
911                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
912                 FROM pg_class AS S,
913                     pg_depend AS D,
914                     pg_class AS T,
915                     pg_attribute AS C,
916                     pg_namespace AS NS
917                 WHERE S.relkind = 'S'
918                     AND S.oid = D.objid
919                     AND D.refobjid = T.oid
920                     AND D.refobjid = C.attrelid
921                     AND D.refobjsubid = C.attnum
922                     AND NS.oid = T.relnamespace
923                 ORDER BY S.relname   
924         ");
925          $cmds = array();
926         while ($cs->fetch()) {
927             $cmds[] = $cs->cmd;
928         }
929         foreach($cmds as $cmd) {
930             $cs = DB_DataObject::factory('core_enum');
931             echo "$cmd\n";
932             $cs->query($cmd);
933         }
934        
935     }
936     
937     var $extensions = array(
938         'EngineCharset',
939         'Links',
940     );
941     
942     function runExtensions()
943     {
944         
945         $ff = HTML_Flexyframework::get();
946         
947         $dburl = parse_url($ff->DB_DataObject['database']);
948         
949         $dbtype = $dburl['scheme'];
950        
951         foreach($this->extensions as $ext) {
952        
953             $scls = ucfirst($dbtype). $ext;
954             $cls = __CLASS__ . '_'. $scls;
955             $fn = implode('/',explode('_', $cls)).'.php';
956             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
957                 return;
958             }
959             require_once $fn;
960             $c = new $cls();
961             
962         }
963         
964     }
965     
966     
967     function checkSystem()
968     {
969         // most of these are from File_Convert...
970         
971         // these are required - and have simple dependancies.
972         require_once 'System.php';
973         $req = array( 
974             'convert',
975             'grep',
976             'pdfinfo',
977             'pdftoppm',
978             'rsvg-convert',  //librsvg2-bin
979             'strings',
980         );
981          
982          
983          
984         // these are prefered - but may have complicated depenacies
985         $pref= array(
986             'abiword',
987             'faad',
988             'ffmpeg',
989             'html2text', // not availabe in debian squeeze
990             'pdftocairo',  //poppler-utils - not available in debian squeeze.
991
992             'lame',
993             'ssconvert',
994             'unoconv',
995             'wkhtmltopdf',
996             'xvfb-run',
997         );
998         $res = array();
999         $fail = false;
1000         foreach($req as $r) {
1001             if (!System::which($r)) {
1002                 $res[] = $r;
1003             }
1004             $fail = true;
1005         }
1006         if ($res) {
1007             $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1008         }
1009         foreach($pref as $r) {
1010             if (!System::which($r)) {
1011                 $res[] = $r;
1012             }
1013             $fail = true;
1014         }
1015         if ($res) {
1016             echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1017             sleep(5);
1018         }
1019         
1020         
1021     }
1022     
1023     
1024 }