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