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