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