]> git.nbdom.net Git - nb.git/commitdiff
Bed
authorNicolas Boisselier <nicolas.boisselier@gmail.com>
Tue, 23 Aug 2016 00:38:03 +0000 (01:38 +0100)
committerNicolas Boisselier <nicolas.boisselier@gmail.com>
Tue, 23 Aug 2016 00:38:03 +0000 (01:38 +0100)
lib/php/db.php
lib/php/db/shell.php
lib/php/db/table.php
lib/php/db/types/sqlite.php
lib/php/out.php

index e2cdf4460daa98459a4b886325a4fee3dfa50da0..eff8166fde37f40317cc1aa4f7a9ea293aab35a7 100644 (file)
@@ -31,7 +31,7 @@ class Db extends nb {
   # Database infos
   public $title;
   public $name;
-  public $type;
+  public static $type;
   public $tables;
   public $row_parse; # Function to call in rows()
 
@@ -55,6 +55,11 @@ class Db extends nb {
       unset($opt['tables']);
     }
 
+    # Statics
+    if (isset($opt['type'])) {
+      self::$type = $opt['type'];
+      unset($opt['type']);
+    }
     # Args
     foreach ($opt as $k=>$v) $this->$k = $v;
 
@@ -106,15 +111,15 @@ class Db extends nb {
   }
 
        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));
-    if (!$this->type) return false;
+    if (empty($this->pdo) and self::$type) $this->pdo = self::$type.':';
+    if (empty(self::$type)) self::$type = strtolower(preg_replace('/^([^:]+):.*$/','\1',$this->pdo));
+    if (!self::$type) return false;
 
     if ($this->type('use_path')) {
       if ($p = $this->p('db.host')) $this->host = $p;
       if (empty($this->host)) $this->host = preg_replace('/^\w+:/','',$this->pdo);
       # Add file
-      if (trim($this->pdo,'pdo:'.$this->type)=='') $this->pdo .= $this->host;
+      if (trim($this->pdo,'pdo:'.self::$type)=='') $this->pdo .= $this->host;
 
     } else {
 
@@ -165,11 +170,11 @@ class Db extends nb {
     if (empty($this->pdo)) return false;
 
     # Type
-    if (!$this->type(null)) $this->bye("Unknow type = `".$this->type."`");
+    if (!$this->type(null)) $this->bye("Unknow type = `".self::$type."`");
 
     # Connect
     if ($this->type('use_path') and !is_readable($this->host)) {
-      $this->bye("Can't read database file `".$this->host."` type=`$this->type`",false);
+      $this->bye("Can't read database file `".$this->host."` type=`".self::$type."`",false);
     }
 
     try {
@@ -321,16 +326,17 @@ class Db extends nb {
 
   public function type($key=null,$die=false,$type=null) {
     global $DB_TYPES;
-    if (!$type) $type = $this->type;
+    if (!$type) $type = self::$type;
 
+    # Load php file
     static $require = array();
     if (empty($require[$type])) {
-      #if (empty($type)) return;
       if (empty($type)) self::bye("Type is required");
       require_once(dirname(__FILE__).'/db/types/'.$type.'.php');
       $require[$type] = 1;
     }
 
+    # Dump all array
     if ($key === null) return $DB_TYPES[$type];
 
     if (empty($DB_TYPES[$type][$key])) {
@@ -346,7 +352,7 @@ class Db extends nb {
     if (!isset($this->tables)) {
       $this->tables = array();
 
-      foreach ($this->conn->query($this->type('tables',true,$this->type),PDO::FETCH_ASSOC) as $row) {
+      foreach ($this->conn->query($this->type('tables',true,self::$type),PDO::FETCH_ASSOC) as $row) {
         $name = current($row);
         $this->tables[$name] = $this->table($name,$row);
       }
@@ -550,34 +556,36 @@ class Db extends nb {
   */
   public static function conf_search_db($conf) {
 
+    $id = self::p('db');
+
     # Load databases
     $conf = self::is_hash($conf) ? $conf : self::conf_dbs($conf);
 
     # Check db=pdo
-    if (preg_match('/^\w+:/',self::p('db'))) {
-      $conf[self::p('db')] = array(
-        'pdo' => self::p('db'),
+    if (preg_match('/^\w+:/',$id)) {
+      $conf[$id] = array(
+        'pdo' => $id,
       );
     }
 
     if (!$conf) return false;
 
     # Param - Default base on order hight num value
-    if (!self::p('db')) {
+    if (!$id) {
       self::pset('db',self::ar_first($conf,true));
     }
 
-    if (!isset($conf[self::p('db')])) {
-      self::bye("Can't find db: `".self::p('db')."` in `".join(",",array_keys($conf))."`",false);
+    if (!isset($conf[$id])) {
+      self::bye("Can't find db: `".$id."` in `".join(",",array_keys($conf))."`",false);
     }
 
-    if (empty($conf[self::p('db')])) return [];
+    if (empty($conf[$id])) return [];
 
     # Construct assoc array
-    $db = array_merge($conf[self::p('db')],array(
-      'dbs'=>array_keys($conf),
-      'conf'=>$conf,
-      'id'=>self::p('db'),
+    $db = array_merge($conf[$id],array(
+      'dbs'  => array_keys($conf),
+      'conf' => $conf,
+      'id'   => $id,
     ));
 
     # Search table
@@ -596,8 +604,8 @@ class Db extends nb {
     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;
+    $db = self::conf_search_db($conf);
 
     # Connection
     $Db->__construct($db);
@@ -687,10 +695,10 @@ class Db extends nb {
     $type_from = $type_to = '';
     if (self::p('db.type')) {
       echo "-- Type     : ".self::p('db.type')."\n";
-      $type_from = $this->type;
+      $type_from = self::$type;
       $type_to = self::p('db.type');
       #$this->type_out = self::p('db.type');
-      $this->type = self::p('db.type');
+      self::$type = self::p('db.type');
       #$this->type_out = self::p('db.type');
     }
 
@@ -732,9 +740,9 @@ class Db extends nb {
       echo $t->sql_create;
 
       if ($insert and $t->type == 'table') {
-        if ($type_from) $this->type = $type_from;
+        if ($type_from) self::$type = $type_from;
         $t->rows();
-        if ($type_to) $this->type = $type_to;
+        if ($type_to) self::$type = $type_to;
       }
     }
 
@@ -750,7 +758,7 @@ class Db extends nb {
     +[
       'id' => (empty($this->id) ? '' : $this->id),
       'name' => $this->name,
-      'type' => $this->type,
+      'type' => self::$type,
       'host' => $this->host,
       #'tables' => count($this->tables()),
       #'conf' => count(array_keys($this->conf)),
index 8a690592115ef4748c7153507b8c410d9cfdd124..3a7a2c6e1249e151fae1fc7fb0812b149b0eda19 100755 (executable)
@@ -2,13 +2,26 @@
 <?php
 define('DB_NO_ACTION',true);
 #require_once(dirname(__FILE__).'/index.php');
+require_once(dirname(__FILE__).'/../config.php');
 require_once(dirname(__FILE__).'/../db.php');
+
+#
+# Default params
+#
 Db::pinit();
+
 # Set format from client Accept if != html
 #bye(out::client_type());
 Db::pdef('format',out::client_type());
 
+#
+# Confs
+#
 $Confs = Db::conf_dbs(array( Db::ROOT_DIR.'/etc/dbs.yaml',Db::ROOT_DIR.'/etc/dbs.php','/etc/dbs.yaml' ));
+
+#
+# Parse stdin
+#
 $Db = null;
 $Table = null;
 #bye(Db::conf_search_db($Conf['ui']));
@@ -28,14 +41,15 @@ while($line = fgets(STDIN)){
 
   }
 
-  if (!db_shell_init($Confs)) {
+  Db::pinit();
+  if (!Db::p('action')) continue;
+  if (true and !db_shell_init($Confs)) {
     echo "ERR: $line\n";
+    continue;
   }
 
-  Db::pinit();
-  die(Db::p('table'));
-  if (!Db::p('action')) continue;
-  var_dump(Db::p());
+  #Db::bye(Db::p());
+  #var_dump(Db::p());
   #echo ">>".$Db->p('action')."\n";
 
   $r = $Db->action($Db->p('action'),$Table);
@@ -46,17 +60,23 @@ while($line = fgets(STDIN)){
 
 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 (Db::p('db') and (
+    $p_db === null or $p_db !== Db::p('db')
+  )) {
     #if (!empty(
+    unset($Table);
+    unset($DB);
+    return Db::init($confs);
     if (!($conf = Db::conf_search_db($confs))) return;
 #unset($conf['dbs']); unset($conf['conf']); bye($conf);
+    #bye($conf);
     $Db = new Db($conf);
     $p_db = Db::p('db');
   }
+  #$r = $Db->action($Db->p('action'),$Table);
+  #bye(var_dump(Db::p(),true));
 
   static $p_table = null;
   if ($p_table === null) $p_table = Db::p('table');
index 788cc70485ec6bceb75e4605cb81b59b336e3084..bd520ef9085fb3f3623f389df282154d5c0d221c 100644 (file)
@@ -1071,6 +1071,8 @@ Class Table extends nb {
     return '</rows>'.NB_EOL;
   }
 
+  public function zaza() { return [ ['A','B'], ['a','bb'] ]; }
+
   /*-----------------------------------------------------------------
     Csv
   -----------------------------------------------------------------*/
@@ -1384,7 +1386,32 @@ Class Table extends nb {
 # NB 23.05.16     };
 
     if ($action == 'table.fields' or $action == 'fields') {
-      return $this->out(array_values($this->object2array($this->fields())));
+      $rows = array_values($this->object2array($this->fields()));
+
+      list($sql,$where,$limit,$select_count) = $this->rows_sql();
+      foreach ([
+        'maxlen' => 'MAX(LENGTH(<NAME>))',
+        'max' => 'MAX(<NAME>)', 
+      ] as $name => $select) {
+        if ($this->p($name)) {
+          $sql = '';
+
+          foreach ($this->fields() as $f) {
+            $sql .= ($sql == '' ? 'SELECT ' : ', '); 
+            $sql .= str_replace('<NAME>',$f->sql_name(),$select);
+          }
+
+          $sql .= ' FROM ' . $this->sql_name() . $where . ($limit ? " LIMIT ".$limit : '');
+          $len = $this->db()->query($sql)->fetch(PDO::FETCH_NUM);
+
+          $i = 0;
+          foreach ($rows as $k => $v) { $rows[$k][$name] = $len[$i]; $i++; }
+
+        }
+      }
+
+      #return $this->out(array_values($this->object2array($this->fields())));
+      return $this->out($rows);
 
     } elseif ($action == 'table.rows' or $action == 'rows') {
       $this->db()->print_header($this->p('format'));
index f44edd10d6afb79ff74169b2faaa31d215a0b32e..7d05b36974449234e1ff77a06ae05a95dbed7081 100644 (file)
@@ -57,7 +57,7 @@ $DB_TYPES['sqlite'] = array (
   'fct' => create_function('&$r',join('',array(
     #'debug("zaza");',
     '$r["key"] = $r["pk"] == "0" ? 0 : 1;',
-    '$r["default"] = $r["dflt_value"];',
+    '$r["default"] = trim($r["dflt_value"],"\'");',
     '$r["null"] = $r["notnull"] == "0" ? 1 : 0;',
     '$r["autoincrement"] = preg_match("/[\(,]\s*".$r["name"]." [^\),]+ AUTOINCREMENT/",$r["this"]->sql()) ? 1 : 0;',
     '$r["extra"] = preg_match("/[\(,]\s*".$r["name"]." \S+ (COLLATE[^,)]+)/",$r["this"]->sql(),$m) ? trim($m[1]) : "";',
index 4e439f787f38419124ceaa94c744e26d6224cddd..2f09d8dd30c636fed2e829a1c3d1decc129da8b5 100644 (file)
@@ -8,6 +8,16 @@ Class Out extends Nb {
   public static $type;
   public static function init() {
     self::$types = array(
+      'human' => [
+        'enclose' => array("","\n"),
+        'eol' => "\n",
+        'sep' => (self::p('sep') ? self::p('sep') : " | "),
+        'line' => '-',
+        'border' => '_',
+        'head' => 'out_human_head',
+        'function' => 'out_human',
+      ],
+
       'sql' => array(),
 
       #'php' => array( 'function' => function(&$r) {var_dump($r);},),
@@ -141,17 +151,40 @@ Class Out extends Nb {
 
     # For sprintf
     unset($o['head_max_len']);
+    if (empty($data)) {
+
+    } else if (self::is_hash($data[0])) {
+
+      $o['head_max_len'] = max(self::ar_map('strlen($a)',array_keys($data[0])));
+
+    } elseif (is_array($data[0])) {
+      #debug($data);
+      $o['head_max_len'] = max(self::ar_map('strlen($a)',$data[0]));
+
+    }
 
-    if (!empty($data)) {
-      if (self::is_hash($data[0])) {
-        $o['head_max_len'] = max(self::ar_map('strlen($a)',array_keys($data[0])));
-      } elseif (is_array($data[0])) {
-        #debug($data);
-        $o['head_max_len'] = max(self::ar_map('strlen($a)',$data[0]));
+    # For no scalar search max length
+    if (self::p('human') and !empty($data) and !is_scalar($data)) {
+      $o['fields_max_len'] = [];
+
+      foreach ($data as $rec) {
+        $i = 0;
+        foreach ($rec as $k=>$v) {
+          if (!is_scalar($v)) continue;
+          if (0
+            or empty($o['fields_max_len'][$i])
+            or strlen($v) > $o['fields_max_len'][$i]
+          ) $o['fields_max_len'][$i] = strlen($v);
+          #echo strlen($v)."\n";
+          $i++;
+        }
       }
-      #bye($o);
+
+      #echo "LENGTH: "; bye( $o['fields_max_len'] );
     }
 
+    #bye($o);
+
     #if (self::p('header')==="0") return;
     if (isset($o['enclose'])) echo $o['enclose'][0];
     if (!isset($o['head'])) return;
@@ -351,25 +384,57 @@ Class Out extends Nb {
   }
 
 } Out::init() ; # < Class
-/****************************************************************************/
+/*--------------------------------------------------------------------------*/
+// Functions
+/*--------------------------------------------------------------------------*/
 
+//
+// Yaml
+//
 function out_yaml(&$row,$o) {
   $yaml = '- '.out::yaml_encode($row);
   $yaml = preg_replace("/^(?!-)/m","  ",$yaml);
   echo $yaml;
 }
 
-function out_csv(&$row,$o) {
+//
+// Human
+//
+function out_human_head(&$row,$o) {
+  if (!is_array($row)) echo 0;
 
-  $values = array();
+  if (out::is_hash($row)) {
+    $ar = array_keys($row);
+    out_human($ar,$o);
+  } else {
+    out_human($row,$o);
+  }
+}
+
+function out_human(&$row,$o) {
+  #debug($o['fields_max_len']);
 
+  if (!count($row)) return;
+  $i = 0;
+  $values = [];
   foreach (array_values($row) as $k=>$v) {
-    $values[] = out::scalar($v);
+    $values[] = sprintf("%"
+      .(empty($o['fields_max_len']) and empty($o['fields_max_len'][$i]) ? '' : '-'.$o['fields_max_len'][$i])
+    ."s",$v);
+    $i++;
   }
 
-  echo str_replace("\n",'\\n',join($o['sep'],$values));
+  #if (count($row))
+  echo ''
+    . ltrim($o['sep'])
+    . join($o['sep'],$values)
+    . rtrim($o['sep'])
+  ;
 }
 
+//
+// Csv
+//
 function out_csv_head(&$row,$o) {
   if (!is_array($row)) echo 0;
   echo "\r";
@@ -381,6 +446,18 @@ function out_csv_head(&$row,$o) {
   }
 }
 
+function out_csv(&$row,$o) {
+
+  $values = array();
+
+  foreach (array_values($row) as $k=>$v) {
+    $values[] = str_replace("\n",'\\n',out::scalar($v));
+  }
+
+  echo join($o['sep'],$values);
+  #echo str_replace("\n",'\\n',join($o['sep'],$values));
+}
+
 function out_tag_head(&$data,$o) {
   #if (isset($o['tag_key'])) return ''; # No header, field will be in rows - NB 24.03.16
   if (isset($o['tag_head'])) $o['tag'] = $o['tag_head'];
@@ -458,5 +535,5 @@ $data = array(
 */
 #$data = array( array('a'=>'A'), array('b'=>'B'), array('c'=>'C') );
 $field = array();
-$o = out::rows(!empty($argv[2]) ? $argv[2] : 'yaml',$data,$field);
+$o = out::rows(!empty($argv[2]) ? $argv[2] : 'csv',$data,$field);
 ?>