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