UpdateDatabase.php
[Pman.Core] / UpdateDatabase.php
index 646c0f0..bfb1690 100644 (file)
@@ -18,31 +18,33 @@ class Pman_Core_UpdateDatabase extends Pman
     static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
  
     static $cli_opts = array(
-        'source' => array(
-            'desc' => 'Source directory for json files.',
-            'short' => 'f',
+      
+        'prefix' => array(
+            'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
+            'short' => 'p',
             'default' => '',
             'min' => 1,
             'max' => 1,
         ),
-        'prefix' => array(
-            'desc' => 'prefix for the passwrod',
+        'data-only' => array(
+            'desc' => 'only run the updateData - do not run import the tables and procedures.',
             'short' => 'p',
             'default' => '',
             'min' => 1,
             'max' => 1,
+            
         ),
-        'name' => array(
-            'desc' => 'name of the company',
+        'add-company' => array(
+            'desc' => 'add a company name of the company',
             'short' => 'n',
             'default' => '',
             'min' => 1,
             'max' => 1,
         ),
-        'comptype' => array(
-            'desc' => 'the type of company',
+        'add-company-with-type' => array(
+            'desc' => 'the type of company (default OWNER)',
             'short' => 't',
-            'default' => '',
+            'default' => 'OWNER',
             'min' => 1,
             'max' => 1,
         ),
@@ -53,7 +55,20 @@ class Pman_Core_UpdateDatabase extends Pman
             'min' => 1,
             'max' => 1,
         ),
+        'only-module-sql' => array(
+            'desc' => 'Only run sql import on this modules - eg. Core',
+            'default' => '',
+            'min' => 1,
+            'max' => 1,
+        ),
         
+        'json-person' => array(
+            'desc' => 'Person JSON file',
+            'default' => '',
+            'min' => 1,
+            'max' => 1,
+            
+        ),
     );
     
     static function cli_opts()
@@ -82,7 +97,7 @@ class Pman_Core_UpdateDatabase extends Pman
         return $ret;
     }
     
-    var $cli_options = false;
+    var $opts = false;
     
     
     var $cli = false;
@@ -104,45 +119,36 @@ class Pman_Core_UpdateDatabase extends Pman
         return true;
     }
      
-    function get($args, $opt)
+    function get($args, $opts)
     {
         
-        $this->cli_options = $opt;
+        PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
+   
         
-        // ask all the modules to verify the opts
+        //$this->fixSequencesPgsql();exit;
+        $this->opts = $opts;
         
-        $this->checkOpts();
+        // ask all the modules to verify the opts
         
+        $this->checkOpts($opts);
         
         
-        if($args == 'Person'){
-            if(empty($opt['source']) || empty($opt['prefix'])){
-                die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
-            }
-            if (!file_exists($opt['source'])) {
-                die("can not found person json file : {$opt['source']} \n");
-            }
-            
-            $persons = json_decode(file_get_contents($opt['source']),true);
-            
-            DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
-            die("DONE! \n");
+     
+        if (empty($opts['data-only'])) {
+            $this->importSQL();
+        }
+        if (!empty($opts['only-module-sql'])) {
+            return;
         }
         
+        $this->runUpdateModulesData();
         
         
-        if($args == 'Company'){
-            if(empty($opt['name']) || empty($opt['comptype'])){
-                die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
-            }
-            
-            DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
-            
-            die("DONE! \n");
+        if (!empty($opts['add-company'])) {
+            // make sure we have a good cache...?
+           
+            DB_DataObject::factory('companies')->initCompanies($this, $opts);
         }
-        
-        $this->importSQL();
-        $this->runUpdateModulesData();
          
     }
     function output() {
@@ -188,9 +194,12 @@ class Pman_Core_UpdateDatabase extends Pman
             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
             ' ' . basename($dburl['path']);
         //echo $mysql_cmd . "\n" ;
+        
+        $files = glob($dir.'/*.sql');
+        uksort($files, 'strcasecmp');
+        
        
-       
-        foreach(glob($dir.'/*.sql') as $fn) {
+        foreach($files as $fn) {
                 
                  
                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
@@ -233,6 +242,10 @@ class Pman_Core_UpdateDatabase extends Pman
         
         foreach($ar as $m) {
             
+            if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
+                continue;
+            }
+            
             $fd = $this->rootDir. "/Pman/$m/DataObjects";
             
             $this->importmysqldir($dburl, $fd);
@@ -263,11 +276,16 @@ class Pman_Core_UpdateDatabase extends Pman
         
         $ar = $this->modulesList();
        
+        print_R($ar);
         foreach($ar as $m) {
-            
+             echo "Importing SQL from module $m\n";
+            if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
+                continue;
+            }
+            echo "Importing SQL from module $m\n";
             // if init has been called
             // look in pgsql.ini
-            if (!empty($this->cli_options['init'])) {
+            if (!empty($this->opts['init'])) {
                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
                 
             }
@@ -287,7 +305,7 @@ class Pman_Core_UpdateDatabase extends Pman
             
             
             
-            if (!empty($this->cli_options['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
+            if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
                 
                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
@@ -319,7 +337,15 @@ class Pman_Core_UpdateDatabase extends Pman
         
         echo $psql_cmd . "\n" ;
         echo "scan : $dir\n";
-        foreach(glob($dir.'/*.sql') as $bfn) {
+        
+        $files = glob($dir.'/*.sql');
+        uksort($files, 'strcasecmp');
+        //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
+        //usort($files, $lsort);
+        
+        
+        
+        foreach($files as $bfn) {
 
 
             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
@@ -458,8 +484,19 @@ class Pman_Core_UpdateDatabase extends Pman
     }
     
     
-    function checkOpts()
+    function checkOpts($opts)
     {
+        
+        
+        foreach($opts as $o=>$v) {
+            if (!preg_match('/^json-/', $o) || empty($v)) {
+                continue;
+            }
+            if (!file_exists($v)) {
+                die("File does not exist : OPTION --{$o} = {$v} \n");
+            }
+        }
+        
         $modules = array_reverse($this->modulesList());
         
         // move 'project' one to the end...
@@ -475,18 +512,40 @@ class Pman_Core_UpdateDatabase extends Pman
             if(!method_exists($x, 'checkOpts')){
                 continue;
             };
-            $x->checkOpts();
+            $x->checkOpts($opts);
         }
                 
     }
-    
+    static function jsonImportFromArray($opts)
+    {
+        foreach($opts as $o=>$v) {
+            if (!preg_match('/^json-/', $o) || empty($v)) {
+                continue;
+            }
+            $type = str_replace('_', '-', substr($o,5));
+            
+            $data= json_decode(file_get_contents($v),true);
+            $pg = HTML_FlexyFramework::get()->page;
+            DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
+            
+        }
+        
+        
+        
+    }
     
     function runUpdateModulesData()
     {
+        
+        
         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
-               
+        echo "Running jsonImportFromArray\n";
+        Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
         
+        
+        echo "Running updateData on modules\n";
         // runs core...
+        echo "Core\n";
         $this->updateData(); 
         $modules = array_reverse($this->modulesList());
         
@@ -497,12 +556,14 @@ class Pman_Core_UpdateDatabase extends Pman
             if($module == 'Core' || !file_exists($file)){
                 continue;
             }
+            
             require_once $file;
             $class = "Pman_{$module}_UpdateDatabase";
             $x = new $class;
             if(!method_exists($x, 'updateData')){
                 continue;
             };
+            echo "$module\n";
             $x->updateData();
         }
                 
@@ -511,7 +572,9 @@ class Pman_Core_UpdateDatabase extends Pman
     
     function updateDataEnums()
     {
+        
         $enum = DB_DataObject::Factory('core_enum');
+        //DB_DAtaObject::debugLevel(1);
         $enum->initEnums(
             array(
                 array(
@@ -628,7 +691,7 @@ class Pman_Core_UpdateDatabase extends Pman
     function updateData()
     {
         // fill i18n data..
-        
+        HTML_FlexyFramework::get()->generateDataobjectsCache(true);
         $this->updateDataEnums();
         $this->updateDataGroups();
         $this->updateDataCompanies();
@@ -642,12 +705,62 @@ class Pman_Core_UpdateDatabase extends Pman
     }
     function fixSequencesPgsql()
     {
-        DB_DataObject::debugLevel(1);
+     
+     
+        //DB_DataObject::debugLevel(1);
+        $cs = DB_DataObject::factory('core_enum');
+        $cs->query("
+         SELECT
+                    'ALTER SEQUENCE '||
+                    CASE WHEN strpos(seq_name, '.') > 0 THEN
+                        min(seq_name)
+                    ELSE 
+                        quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
+                    END 
+                    
+                    ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
+                    quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
+             FROM (
+                      
+                       SELECT 
+                     n.nspname AS schema_name,
+                     c.relname AS table_name,
+                     a.attname AS column_name, 
+                     regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
+                 FROM pg_class c 
+                 JOIN pg_attribute a ON (c.oid=a.attrelid) 
+                 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
+                 JOIN pg_namespace n ON (c.relnamespace=n.oid)
+                 WHERE has_schema_privilege(n.oid,'USAGE')
+                   AND n.nspname NOT LIKE 'pg!_%' escape '!'
+                   AND has_table_privilege(c.oid,'SELECT')
+                   AND (NOT a.attisdropped)
+                   AND d.adsrc ~ '^nextval'
+              
+             ) seq
+             WHERE
+                 CASE WHEN strpos(seq_name, '.') > 0 THEN
+                     substring(seq_name, 1,strpos(seq_name,'.')-1)
+                ELSE
+                    schema_name
+                END = schema_name
+             
+             GROUP BY seq_name HAVING count(*)=1
+             ");
+        $cmds = array();
+        while ($cs->fetch()) {
+            $cmds[] = $cs->cmd;
+        }
+        foreach($cmds as $cmd) {
+            $cs = DB_DataObject::factory('core_enum');
+            echo "$cmd\n";
+            $cs->query($cmd);
+        }
         $cs = DB_DataObject::factory('core_enum');
          $cs->query("
                SELECT  'SELECT SETVAL(' ||
                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
-                        ', MAX(' || quote_ident(C.attname)|| ') )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
+                        ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
                 FROM pg_class AS S,
                     pg_depend AS D,
                     pg_class AS T,
@@ -659,19 +772,18 @@ class Pman_Core_UpdateDatabase extends Pman
                     AND D.refobjid = C.attrelid
                     AND D.refobjsubid = C.attnum
                     AND NS.oid = T.relnamespace
-                ORDER BY S.relname;     
+                ORDER BY S.relname   
         ");
+         $cmds = array();
         while ($cs->fetch()) {
             $cmds[] = $cs->cmd;
         }
         foreach($cmds as $cmd) {
             $cs = DB_DataObject::factory('core_enum');
+            echo "$cmd\n";
             $cs->query($cmd);
         }
-        
-         
-        
-        
+       
     }
     
 }
\ No newline at end of file