# Database infos
public $title;
public $name;
- public $type;
+ public static $type;
public $tables;
public $row_parse; # Function to call in rows()
unset($opt['tables']);
}
+ # Statics
+ if (isset($opt['type'])) {
+ self::$type = $opt['type'];
+ unset($opt['type']);
+ }
# Args
foreach ($opt as $k=>$v) $this->$k = $v;
}
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 {
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 {
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])) {
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);
}
*/
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
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);
$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');
}
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;
}
}
+[
'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)),
<?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']));
}
- 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);
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');
return '</rows>'.NB_EOL;
}
+ public function zaza() { return [ ['A','B'], ['a','bb'] ]; }
+
/*-----------------------------------------------------------------
Csv
-----------------------------------------------------------------*/
# 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'));
'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]) : "";',
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);},),
# 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;
}
} 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";
}
}
+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'];
*/
#$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);
?>