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