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