]> git.nbdom.net Git - nb.git/commitdiff
shell.sh
authorNicolas Boisselier <nicolas.boisselier@semantico.com>
Fri, 12 Aug 2016 16:24:15 +0000 (17:24 +0100)
committerNicolas Boisselier <nicolas.boisselier@semantico.com>
Fri, 12 Aug 2016 16:24:15 +0000 (17:24 +0100)
lib/php/db.php
lib/php/db/shell.php
lib/php/db/table.php

index a863fe077b501eb2604149e073f74de120395808..468d2f05ba32c78f6eda853d0036d1a6706b6224 100644 (file)
@@ -35,9 +35,6 @@ class Db extends nb {
   public $tables;
   public $row_parse; # Function to call in rows()
 
-  # Objects
-# NB 28.03.16   public $table;
-
   # Web
   public $default_table;
   public $sort;
@@ -103,6 +100,11 @@ class Db extends nb {
     return true;
   }
 
+  public function __destruct() {
+    foreach (array_keys((array)$this) as $k) { if (isset($this->$k)) unset($this->$k); };
+    $this->disconnect();
+  }
+
        function connect_init() {
     if (empty($this->pdo) and $this->type) $this->pdo = $this->type.':';
     if (empty($this->type)) $this->type = strtolower(preg_replace('/^([^:]+):.*$/','\1',$this->pdo));
@@ -150,6 +152,11 @@ class Db extends nb {
     # Title
     if (empty($this->title)) $this->title = prettyText($this->name);
 
+  }
+
+       function disconnect() {
+    if (empty($this->conn)) return null;
+    return $this->conn->close();
   }
 
        function connect() {
@@ -277,13 +284,17 @@ class Db extends nb {
     return $this->conn->quote($v);
   }
 
+  /**
+  * @author NB 12.08.16
+  * Return a table instance
+  */
   function table($name,$opt=array()) {
     if ($this->tables() and array_key_exists($name,$this->tables)) {
-      #if ($opt) bye($opt);
       if ($opt) $this->tables[$name]->__construct($name,$opt);
       return $this->tables[$name];
     }
-    return new Table($name,$opt);
+
+    return new Table($name,$opt+['db'=>$this]);
   }
 
   public function localFile() {
@@ -368,7 +379,6 @@ class Db extends nb {
     $available = [
       ['(db.)?help','This help'],
       ['(db.)?dbs','List databases from conf'],
-      #['(db.)?dbs','List databases (name=* type=* all=1)'],
       ['(db.)?tables','List tables (name=* type=* count=1 engine=*)'],
 
       ['(table.)?rows','Dump one table, use format='],
@@ -404,7 +414,17 @@ class Db extends nb {
             if (!empty($type) and !$this->str_match($t->type,$type)) continue;
             if (!empty($count) and !$this->str_match($t->count,$count)) continue;
             if (!empty($engine) and !$this->str_match($t->engine,$engine)) continue;
-            $rows[] = $t->infos();
+
+            $rows[] =  []
+              +[
+                'name' => $t->name,
+                'type' => $t->type,
+              ]
+              +$t->infos()
+              +( self::p('fields') ?['fields' => count($t->fields())] : [] )
+              +( self::p('count') ?['count' => $t->count()] : [] )
+              +( self::p('sql') ? ['sql' => $t->sql()] : [] )
+            ;
           }
 
           usort($rows,function($a,$b) { return strcmp($a['name'],$b['name']); });
@@ -515,45 +535,62 @@ class Db extends nb {
     return $h;
   }
 
-  //
-  // Create globals from $conf=array(yaml_fileds)
-  //
-  public static function init($conf) {
-    global $Db, $Table;
-
-    if (isset($Table)) self::bye("Table.init(): GLOBALS['Table'] already exists !");
-    if (isset($Db)) self::bye("Db.init(): GLOBALS['Db'] already exists !");
-
-    $Db = new self();
+  /**
+  * @copyright NB 12.08.16
+  * Return a db hash to create a new instance from $conf
+  */
+  public static function conf_search_db($conf) {
 
     # Load databases
-    $conf = self::is_hash($conf) ? $conf : $Db->conf_dbs($conf);
+    $conf = self::is_hash($conf) ? $conf : self::conf_dbs($conf);
 
     # Check db=pdo
-    if (preg_match('/^\w+:/',$Db->p('db'))) {
-      $conf[$Db->p('db')] = array(
-        'pdo' => $Db->p('db'),
+    if (preg_match('/^\w+:/',self::p('db'))) {
+      $conf[self::p('db')] = array(
+        'pdo' => self::p('db'),
       );
     }
 
     if (!$conf) return false;
 
     # Param - Default base on order hight num value
-    if (!$Db->p('db')) {
-      $Db->pset('db',$Db->ar_first($conf,true));
+    if (!self::p('db')) {
+      self::pset('db',self::ar_first($conf,true));
     }
 
-    if (!isset($conf[$Db->p('db')])) {
-      $Db->bye("Can't find db: `".$Db->p('db')."` in `".join(",",array_keys($conf))."`",false);
+    if (!isset($conf[self::p('db')])) {
+      self::bye("Can't find db: `".self::p('db')."` in `".join(",",array_keys($conf))."`",false);
     }
 
-    # Connection
-    $db = array_merge($conf[$Db->p('db')],array(
+    if (empty($conf[self::p('db')])) return [];
+
+    # Construct assoc array
+    $db = array_merge($conf[self::p('db')],array(
       'dbs'=>array_keys($conf),
       'conf'=>$conf,
-      'id'=>$Db->p('db'),
+      'id'=>self::p('db'),
     ));
 
+    # Search table
+    #$table = Db::p('table');
+
+    return $db;
+  }
+
+  /**
+  * @copyright NB 12.08.16
+  * Create globals Db and Table
+  */
+  public static function init($conf) {
+    global $Db, $Table;
+    if (isset($Table)) self::bye("Table.init(): GLOBALS['Table'] already exists !");
+    if (isset($Db)) self::bye("Db.init(): GLOBALS['Db'] already exists !");
+    $Db = new self();
+
+    $db = self::conf_search_db($conf);
+    if (empty($Db)) return false;
+
+    # Connection
     $Db->__construct($db);
 
     if (empty($Db->pdo)) $Db->bye("No pdo for db: `".$Db->p('db')."`");
@@ -561,24 +598,34 @@ class Db extends nb {
     /*
       Table
     */
-    if (empty($Db)) return false;
     if (self::p('action') and
       !self::p('table') and
       !preg_match('/^(table\.\w+|rows|insert|edit|delete|update)$/',self::p('action'))
-    ) return true;
-    if (!$Db->p('table') and isset($Db->default_table)) $Db->pset('table',$Db->default_table);
-    if (!$Db->p('table') and ($v = array_keys($Db->tables()))) $Db->pset('table',$Db->ar_first($v));
+    ) {
+    } else {
 
-    if (empty($db['tables'][$Db->p('table')])) $db['tables'][$Db->p('table')] = array();
-    if ($Db->p('table')) $Table = $Db->table($Db->p('table'),$db['tables'][$Db->p('table')]);
+      # Search default_table
+      if (!self::p('table') and isset($Db->default_table)) self::pset('table',$Db->default_table);
 
-    return true;
+      # Choose first table
+      if (!self::p('table') and ($v = array_keys($Db->tables()))) self::pset('table',$Db->ar_first($v));
+
+      if ($Db->p('table')) $Table = $Db->table($Db->p('table'),
+        ( empty($db['tables'][$Db->p('table')]) ? [] : $db['tables'][$Db->p('table')] )
+      );
 
+    }
+
+    return true;
   }
 
+  /**
+  * @copyright NB 12.08.16
+  * Transform pdo string into assoc array
+  */
   public function pdo_info() {
     return preg_replace_callback('/(\w+)=([^;]*)(;?)/',function($m){
-      return preg_match('/^(host|dbname|name)/',$m[1]) ? $m[0] : ''; 
+      return preg_match('/^(host|dbname|name)/',$m[1]) ? $m[0] : '';
     },$this->pdo);
   }
 
@@ -602,6 +649,7 @@ class Db extends nb {
     # Cache before changing db type
     $views = [];
     foreach ($tables as $k=>$t) {
+
       if (
         ($t->type != 'table' and $t->type != 'view')
         or (!empty($name) and !$this->str_match($t->name,$name))
@@ -610,8 +658,10 @@ class Db extends nb {
         unset($tables[$k]);
         continue;
       }
+
       if ($t->type == 'view') $views[] = $t->name;
       unset($t->orderby);
+
       $t->fields();
       $t->sql();
     }
@@ -724,7 +774,7 @@ return;
       'type' => $this->type,
       'host' => $this->host,
       #'tables' => count($this->tables()),
-      #'dbs' => count(array_keys($this->conf)),
+      #'conf' => count(array_keys($this->conf)),
       'tables' => count($this->tables()),
     ]
     +($this->type('use_path') ? array() : array(
@@ -842,7 +892,7 @@ return;
   }
 
   public static function pinit() {
-    Db::paliases(array(
+    self::paliases(array(
       'd' => 'db',
       't' => 'table',
       'f' => 'format',
@@ -852,12 +902,12 @@ return;
       'h' => 'header',
     ));
 
-    #if($format = out::client_type()) Db::pset('format',$format);
+    #if($format = out::client_type()) self::pset('format',$format);
 
     # Param - Extract dbname from table
-    if (preg_match('/^(\w+)\.(.*?)$/',Db::p('table'),$m)) {
-      Db::pset('db',$m[1]);
-      Db::pset('table',$m[2]);
+    if (preg_match('/^(\w+)\.(.*?)$/',self::p('table'),$m)) {
+      self::pset('db',$m[1]);
+      self::pset('table',$m[2]);
     }
 
   }
index 4e07e899a223a7e714d6c306d8e3f8cd9c2d8705..8a690592115ef4748c7153507b8c410d9cfdd124 100755 (executable)
@@ -8,10 +8,12 @@ Db::pinit();
 #bye(out::client_type());
 Db::pdef('format',out::client_type());
 
-$Conf = Db::conf_dbs(array( Db::ROOT_DIR.'/etc/dbs.yaml',Db::ROOT_DIR.'/etc/dbs.php','/etc/dbs.yaml' ));
+$Confs = Db::conf_dbs(array( Db::ROOT_DIR.'/etc/dbs.yaml',Db::ROOT_DIR.'/etc/dbs.php','/etc/dbs.yaml' ));
 $Db = null;
 $Table = null;
+#bye(Db::conf_search_db($Conf['ui']));
 
+#bye($Confs['ui']);
 while($line = fgets(STDIN)){
 
   # Set params
@@ -21,10 +23,15 @@ while($line = fgets(STDIN)){
 
     array_shift($args);
     #var_dump($args);
-    $Db->pset($args[0],$args[1]);
+    Db::pset($args[0],$args[1]);
     $line = mb_substr($line,mb_strlen($line)-1);
 
   }
+
+  if (!db_shell_init($Confs)) {
+    echo "ERR: $line\n";
+  }
+
   Db::pinit();
   die(Db::p('table'));
   if (!Db::p('action')) continue;
@@ -35,5 +42,26 @@ while($line = fgets(STDIN)){
   #foreach ($args
 
 
+}
+
+function db_shell_init($confs) {
+  global $Db, $Table;
+  Db::pinit();
+
+
+  static $p_db = null;
+  if ($p_db === null or $p_db !== Db::p('db')) {
+    #if (!empty(
+    if (!($conf = Db::conf_search_db($confs))) return;
+#unset($conf['dbs']); unset($conf['conf']); bye($conf);
+    $Db = new Db($conf);
+    $p_db = Db::p('db');
+  }
+
+  static $p_table = null;
+  if ($p_table === null) $p_table = Db::p('table');
+
+  bye([$p_db,$p_table]);
+
 }
 ?>
index e8932f992e6b5b97162ee22f9f2e7d81be117550..49958e4d635a3f6912905732b0444d8ed0214230 100644 (file)
@@ -61,13 +61,7 @@ Class Table extends nb {
       $this->sql = $opt['sql']; unset($opt['sql']);
     }
 
-    // Extras
-    if (isset($opt['extras'])) {
-      $this->add_extras($opt['extras']);
-      unset($opt['extras']);
-    }
-
-    // Connection
+    // Db / Connection
     if (isset($opt['db'])) {
       $this->db(is_object($opt['db']) ? $opt['db'] : new Db($opt['db']));
       unset($opt['db']);
@@ -80,6 +74,12 @@ Class Table extends nb {
 
     }
 
+    // Extras
+    if (isset($opt['extras'])) {
+      $this->add_extras($opt['extras']);
+      unset($opt['extras']);
+    }
+
     // Add others
     foreach ($opt as $k => $v) { $this->$k = $v; }
 
@@ -628,7 +628,8 @@ Class Table extends nb {
     if ($this->p('extras') === '0') return false;
     #return false;
 
-    $this->fields();
+    # Test if type exists because of a bug from shell.php
+    if ($this->db()->type) $this->fields();
 
     foreach ($extras as $k => $v) {
 
@@ -1346,15 +1347,12 @@ Class Table extends nb {
       array(
         "name" => $this->name,
         "type" => $this->type,
-        "fields" => count($this->fields()),
+        #"fields" => count($this->fields()),
         #"count" => $this->count(),
         #"sql_name" => $this->sql_name(),
       )
-      +( self::p('count') ? array("count" => $this->count()) : array() )
       +( isset($this->engine) ? array("engine" => $this->engine) : array() )
       +( isset($this->created) ? array("created" => $this->created) : array() )
-      +( self::p('sql') ? array("sql" => $this->sql()) : array() )
-      #+( self::p('sql') ? array("sql" => $this->sql()) : array() )
     ;
   }