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