UpdateDatabase.php
[Pman.Core] / UpdateDatabase.php
index d25ddec..79de922 100644 (file)
@@ -45,10 +45,60 @@ class Pman_Core_UpdateDatabase extends Pman
             'default' => '',
             'min' => 1,
             'max' => 1,
-        )
+        ),
+        'init' => array(
+            'desc' => 'Initialize the database (pg only supported)',
+            'short' => 'i',
+            'default' => '',
+            'min' => 1,
+            'max' => 1,
+        ),
         
+        'json-company' => array(
+            'desc' => 'Company JSON file',
+            'default' => '',
+            'min' => 1,
+            'max' => 1,
+            
+        ),
+        'json-person' => array(
+            'desc' => 'Person JSON file',
+            'default' => '',
+            'min' => 1,
+            'max' => 1,
+            
+        ),
     );
     
+    static function cli_opts()
+    {
+        
+        $ret = self::$cli_opts;
+        $ff = HTML_FlexyFramework::get();
+        $a = new Pman();
+        $mods = $a->modulesList();
+        foreach($mods as $m) {
+            
+            $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
+            if (!file_exists($fd)) {
+                continue;
+            }
+            
+            require_once $fd;
+            
+            $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
+            
+            $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
+            
+            
+        }
+        
+        return $ret;
+    }
+    
+    var $opts = false;
+    
+    
     var $cli = false;
     function getAuth() {
         
@@ -70,6 +120,15 @@ class Pman_Core_UpdateDatabase extends Pman
      
     function get($args, $opt)
     {
+        
+        $this->opts = $opt;
+        
+        // ask all the modules to verify the opts
+        
+        $this->checkOpts($opt);
+        
+        
+        
         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");
@@ -84,6 +143,8 @@ class Pman_Core_UpdateDatabase extends Pman
             die("DONE! \n");
         }
         
+        
+        
         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");
@@ -206,7 +267,7 @@ class Pman_Core_UpdateDatabase extends Pman
     /**
      * postgresql import..
      */
-    function importpgsql($url)
+    function importpgsql($dburl)
     {
         
         // hide stuff for web..
@@ -216,7 +277,16 @@ class Pman_Core_UpdateDatabase extends Pman
         
         $ar = $this->modulesList();
        
-         foreach($ar as $m) {
+        foreach($ar as $m) {
+            
+            // if init has been called
+            // look in pgsql.ini
+            if (!empty($this->opts['init'])) {
+                $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
+                
+            }
+            
+            
             
             $fd = $this->rootDir. "/Pman/$m/DataObjects";
             
@@ -228,13 +298,23 @@ class Pman_Core_UpdateDatabase extends Pman
             
             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
+            
+            
+            
+            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");
+                $this->fixSequencesPgsql();
+                
+            }
               
             
         }
        
           
     }
-    function importpgsqldir($url, $dir)
+    function importpgsqldir($url, $dir, $disable_triggers = false)
     {
         require_once 'System.php';
         $cat = System::which('cat');
@@ -249,7 +329,10 @@ class Pman_Core_UpdateDatabase extends Pman
             ' -h ' . $url['host'] .
             ' -U' . escapeshellarg($url['user']) .
              ' ' . basename($url['path']);
+        
+        
         echo $psql_cmd . "\n" ;
+        echo "scan : $dir\n";
         foreach(glob($dir.'/*.sql') as $bfn) {
 
 
@@ -263,7 +346,7 @@ class Pman_Core_UpdateDatabase extends Pman
             }
             $fn = false;
 
-            if (basename($dir) != 'pgsql') {
+            if (!preg_match('/pgsql/', basename($dir) )) {
                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
                     $fn = $this->convertToPG($bfn);
                 }
@@ -325,23 +408,18 @@ class Pman_Core_UpdateDatabase extends Pman
               
             }
             
-            // enum value
-            if ($tbl && preg_match('#alter\s+table\s+#i',  $l, $m)) {
-                
-                if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
-                    $extra[] = "CREATE TYPE {$tbl}_{$m[1]}_enum AS {$m[2]};";
-                    continue;
-                }
-                
-                if (preg_match('#(\`[a-z0-9_]+\`)#i',  $l, $m)){
-                    
-                }
-                
-            }else{
-                
-                if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
-                    $l = preg_replace('#enum\([\w|\W]+\)#i', "{$tbl}_{$m[1]}_enum", $l);
-                }
+            if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
+                $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
+            }
+            
+            // enum value -- use the text instead..
+            
+            if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
+                $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
+            }
+            // ignore the alter enum
+            if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
+                continue;
             }
             
             // UNIQUE KEY .. ignore
@@ -368,7 +446,7 @@ class Pman_Core_UpdateDatabase extends Pman
             }
             
             // CREATE INDEX ..ignore
-            if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+([^(]+)(.*)$#i',  $l, $m)) {
+            if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
                 continue;
              }
@@ -386,16 +464,74 @@ class Pman_Core_UpdateDatabase extends Pman
         }
         
         $ret = array_merge($extra,$ret);
-        echo implode("\n", $ret); exit;
+//        echo implode("\n", $ret); exit;
         
         file_put_contents($fn, implode("\n", $ret));
         
         return $fn;
     }
     
+    
+    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...
+        
+        foreach ($modules as $module){
+            $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
+            if($module == 'Core' || !file_exists($file)){
+                continue;
+            }
+            require_once $file;
+            $class = "Pman_{$module}_UpdateDatabase";
+            $x = new $class;
+            if(!method_exists($x, 'checkOpts')){
+                continue;
+            };
+            $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,6));
+            $data= json_decode(file_get_contents($file),true);
+            DB_DataObject::factory($type)->importFromArray($data);
+            
+        }
+        
+        
+        
+    }
+    
     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());
         
@@ -406,12 +542,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();
         }
                 
@@ -542,12 +680,45 @@ class Pman_Core_UpdateDatabase extends Pman
         $this->updateDataGroups();
         $this->updateDataCompanies();
         
-       
+        $c = DB_DataObject::Factory('I18n');
+        $c->buildDB();
          
        
         
         
     }
-    
+    function fixSequencesPgsql()
+    {
+        DB_DataObject::debugLevel(1);
+        $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 
+                FROM pg_class AS S,
+                    pg_depend AS D,
+                    pg_class AS T,
+                    pg_attribute AS C,
+                    pg_namespace AS NS
+                WHERE S.relkind = 'S'
+                    AND S.oid = D.objid
+                    AND D.refobjid = T.oid
+                    AND D.refobjid = C.attrelid
+                    AND D.refobjsubid = C.attnum
+                    AND NS.oid = T.relnamespace
+                ORDER BY S.relname;     
+        ");
+        while ($cs->fetch()) {
+            $cmds[] = $cs->cmd;
+        }
+        foreach($cmds as $cmd) {
+            $cs = DB_DataObject::factory('core_enum');
+            $cs->query($cmd);
+        }
+        
+         
+        
+        
+    }
     
 }
\ No newline at end of file