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         
152         $this->runUpdateModulesData();
153         
154         
155         if (!empty($opts['add-company'])) {
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         
562         
563         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
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         $modules = array_reverse($this->modulesList());
573         
574         // move 'project' one to the end...
575         
576         foreach ($modules as $module){
577             if(in_array($module, $this->disabled)){
578                 continue;
579             }
580             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
581             if($module == 'Core' || !file_exists($file)){
582                 continue;
583             }
584             
585             require_once $file;
586             $class = "Pman_{$module}_UpdateDatabase";
587             $x = new $class;
588             if(!method_exists($x, 'updateData')){
589                 continue;
590             };
591             echo "$module\n";
592             $x->updateData();
593         }
594                 
595     }
596     
597     
598     function updateDataEnums()
599     {
600         
601         $enum = DB_DataObject::Factory('core_enum');
602         //DB_DAtaObject::debugLevel(1);
603         $enum->initEnums(
604             array(
605                 array(
606                     'etype' => '',
607                     'name' => 'COMPTYPE',
608                     'display_name' =>  'Company Types',
609                     'is_system_enum' => 1,
610                     'cn' => array(
611                         array(
612                             'name' => 'OWNER',
613                             'display_name' => 'Owner',
614                             'seqid' => 999, // last...
615                             'is_system_enum' => 1,
616                         )
617                         
618                     )
619                 ),
620                 array(
621                     'etype' => '',
622                     'name' => 'HtmlEditor.font-family',
623                     'display_name' =>  'HTML Editor font families',
624                     'is_system_enum' => 1,
625                     'cn' => array(
626                         array(
627                             'name' => 'Helvetica,Arial,sans-serif',
628                             'display_name' => 'Helvetica',
629                             
630                         ),
631                         
632                         array(
633                             'name' => 'Courier New',
634                             'display_name' => 'Courier',
635                              
636                         ),
637                         array(
638                             'name' => 'Tahoma',
639                             'display_name' => 'Tahoma',
640                             
641                         ),
642                         array(
643                             'name' => 'Times New Roman,serif',
644                             'display_name' => 'Times',
645                            
646                         ),
647                         array(
648                             'name' => 'Verdana',
649                             'display_name' => 'Verdana',
650                             
651                         ),
652                         
653                             
654                         
655                     )
656                 ),
657             )
658         ); 
659         
660     }
661     function updateDataGroups()
662     {
663          
664         $groups = DB_DataObject::factory('groups');
665         $groups->initGroups();
666         
667         $groups->initDatabase($this,array(
668             array(
669                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
670                 'type' => 0, // system
671             ),
672             array(
673                 'name' => 'system-email-from',
674                 'type' => 0, // system
675             ),
676             array(
677                 'name' => 'core-person-signup-bcc',
678                 'type' => 0, // system
679             ),
680         ));
681         
682     }
683     
684     function updateDataCompanies()
685     {
686          
687         // fix comptypes enums..
688         $c = DB_DataObject::Factory('Companies');
689         $c->selectAdd();
690         $c->selectAdd('distinct(comptype) as comptype');
691         $c->whereAdd("comptype != ''");
692         
693         $ctb = array();
694         foreach($c->fetchAll('comptype') as $cts) {
695             
696             
697             
698            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
699         
700         }
701          $c = DB_DataObject::Factory('core_enum');
702          
703         $c->initEnums($ctb);
704         //DB_DataObject::debugLevel(1);
705         // fix comptypeid
706         $c = DB_DataObject::Factory('Companies');
707         $c->query("
708             UPDATE Companies 
709                 SET
710                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
711                 WHERE
712                     comptype_id = 0
713                     AND
714                     LENGTH(comptype) > 0
715                   
716                   
717                   ");
718          
719         
720         
721     }
722     
723     function updateData()
724     {
725         // fill i18n data..
726         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
727         $this->updateDataEnums();
728         $this->updateDataGroups();
729         $this->updateDataCompanies();
730         
731         $c = DB_DataObject::Factory('I18n');
732         $c->buildDB();
733          
734        
735         
736         
737     }
738     
739     function fixMysqlInnodb()
740     {
741         
742         static $done_check = false;
743         if ($done_check) {
744             return;
745         }
746         // innodb in single files is far more efficient that MYD or one big innodb file.
747         // first check if database is using this format.
748         $db = DB_DataObject::factory('core_enum');
749         $db->query("show variables like 'innodb_file_per_table'");
750         $db->fetch();
751         if ($db->Value == 'OFF') {
752             die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
753         }
754         
755         $done_check = true;;
756
757  
758         
759         
760         
761         
762         
763     }
764     
765     
766     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
767     
768     function fixSequencesMysql()
769     {
770         // not required...
771     }
772     
773     function fixSequencesPgsql()
774     {
775      
776      
777         //DB_DataObject::debugLevel(1);
778         $cs = DB_DataObject::factory('core_enum');
779         $cs->query("
780          SELECT
781                     'ALTER SEQUENCE '||
782                     CASE WHEN strpos(seq_name, '.') > 0 THEN
783                         min(seq_name)
784                     ELSE 
785                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
786                     END 
787                     
788                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
789                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
790              FROM (
791                       
792                        SELECT 
793                      n.nspname AS schema_name,
794                      c.relname AS table_name,
795                      a.attname AS column_name, 
796                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
797                  FROM pg_class c 
798                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
799                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
800                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
801                  WHERE has_schema_privilege(n.oid,'USAGE')
802                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
803                    AND has_table_privilege(c.oid,'SELECT')
804                    AND (NOT a.attisdropped)
805                    AND d.adsrc ~ '^nextval'
806               
807              ) seq
808              WHERE
809                  CASE WHEN strpos(seq_name, '.') > 0 THEN
810                      substring(seq_name, 1,strpos(seq_name,'.')-1)
811                 ELSE
812                     schema_name
813                 END = schema_name
814              
815              GROUP BY seq_name HAVING count(*)=1
816              ");
817         $cmds = array();
818         while ($cs->fetch()) {
819             $cmds[] = $cs->cmd;
820         }
821         foreach($cmds as $cmd) {
822             $cs = DB_DataObject::factory('core_enum');
823             echo "$cmd\n";
824             $cs->query($cmd);
825         }
826         $cs = DB_DataObject::factory('core_enum');
827          $cs->query("
828                SELECT  'SELECT SETVAL(' ||
829                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
830                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
831                 FROM pg_class AS S,
832                     pg_depend AS D,
833                     pg_class AS T,
834                     pg_attribute AS C,
835                     pg_namespace AS NS
836                 WHERE S.relkind = 'S'
837                     AND S.oid = D.objid
838                     AND D.refobjid = T.oid
839                     AND D.refobjid = C.attrelid
840                     AND D.refobjsubid = C.attnum
841                     AND NS.oid = T.relnamespace
842                 ORDER BY S.relname   
843         ");
844          $cmds = array();
845         while ($cs->fetch()) {
846             $cmds[] = $cs->cmd;
847         }
848         foreach($cmds as $cmd) {
849             $cs = DB_DataObject::factory('core_enum');
850             echo "$cmd\n";
851             $cs->query($cmd);
852         }
853        
854     }
855     
856     var $extensions = array(
857         'EngineCharset',
858         'Links',
859     );
860     
861     function runExtensions()
862     {
863         
864         $ff = HTML_Flexyframework::get();
865         
866         $dburl = parse_url($ff->DB_DataObject['database']);
867         
868         $dbtype = $dburl['scheme'];
869        
870         foreach($this->extensions as $ext) {
871        
872             $scls = ucfirst($dbtype). $ext;
873             $cls = __CLASS__ . '_'. $scls;
874             $fn = implode('/',explode('_', $cls)).'.php';
875             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
876                 return;
877             }
878             require_once $fn;
879             $c = new $cls();
880             
881         }
882         
883     }
884 }