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