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