]> git.nbdom.net Git - nb.git/commitdiff
Split DB_TYPES for individual load
authorNicolas Boisselier <nicolas.boisselier@gmail.com>
Tue, 29 Mar 2016 01:46:20 +0000 (02:46 +0100)
committerNicolas Boisselier <nicolas.boisselier@gmail.com>
Tue, 29 Mar 2016 01:46:20 +0000 (02:46 +0100)
12 files changed:
etc/dbs.yaml
lib/js/nb.js
lib/php/benchmark.php
lib/php/db.php
lib/php/db/index.php
lib/php/db/table.php
lib/php/db/types.php
lib/php/db/types/mysql.php [new file with mode: 0644]
lib/php/db/types/pgsql.php [new file with mode: 0644]
lib/php/db/types/sqlite.php [new file with mode: 0644]
lib/php/nb.php
lib/php/out.php

index b5d4dc925a10a879f2a43dba6dd89d748230ae00..9178b6181c43928266f4dfc83d2a28e781a1d9ed 100644 (file)
@@ -22,7 +22,6 @@ puppetdb:
   title: Puppetdb
   host: big
   type: pgsql
-  name: puppetdb
   user: puppetdb
   default_table: view_hosts
   tables:
index cbf10a2df746d8798ece38704d13af0b0bb08786..a6ec6a793ff7a61cdb5cfe17487a964fa866ee69 100644 (file)
@@ -4,18 +4,28 @@
  * Date: 28.03.15
  * See: http://www.w3schools.com/jquery/jquery_ref_selectors.asp
  */
+
 function NB() {
 
   var that = this;
+  var name = 'Nb';
 
   this.ready = function() {
 
-    // Behavior
+    // Form clean
     $('form').submit(function(e){
       //e.preventDefault();
       return that.form_submit_clean(this);
     });
 
+    // Add msg div
+    var msg = $('<div id="nb-msg"></div>');
+    if ($('h1').length) {
+      msg.insertAfter('h1:first');
+    } else {
+      $('body').prepend(msg);
+    }
+
     // Used in css to trigger a resize
     $('body').append('<span id="_responsive" style="display:none"></span>');
 
@@ -318,7 +328,7 @@ function NB() {
       if ($.isArray(data) && data.length == 1) data = data[0];
       var html = that.data2html(data);
       //console.log(that.data2html(data));
-      if (html != '') $(html).prependTo( "#msg" );
+      if (html != '') $(html).prependTo( "#nb-msg" );
       //console.log(typeof(data));
     });
   }
@@ -347,6 +357,13 @@ function NB() {
                }
                return dumped_text;
        }
+
+  this.msg = function(msg) {
+    $('<p>'+msg+'</p>').prependTo( "#nb-msg" );
+  }
+
 };
+/*
+*/
 
 //NB.prototype.your_method = function() { }
index 8c4789c0f89adc316a4194a536cabd61e3e0284e..4e4b526258ea8fc848f7e1ac6c10e0f4d29b7467 100755 (executable)
@@ -6,6 +6,9 @@ if (0) die(
 );
 require(dirname(__FILE__).'/nb.php');
 $_GET['var'] = 'sldkfhlsakhlshglzkdhzfgldznfdznbldzknb';
+$array = array_fill(0,100000,"a");
+$hash = array(); for ($i=0;$i<100000;$i++) $hash[$i] = $i;
+echo "Start benchmark\n";
 
 /*
 $a = array('a' => 'A');
@@ -23,13 +26,14 @@ exit;
 #function _strpos() { strpos('zaza',$_GET['var']) !== false; } nb::benchmark('_strpos');
 #function _static() { static $var = null; if ($var===null) $var='zaza'; } nb::benchmark('_static');
 #function _global() { if ($_GLOBAL['var'] === null) $var='zaza'; } nb::benchmark('_global');
-function _empty() { empty($var); } nb::benchmark('_empty');
-function _isset() { isset($var); } nb::benchmark('_isset');
+#function _empty() { empty($var); } nb::benchmark('_empty',5000000);
+#function _isset() { isset($var); } nb::benchmark('_isset',5000000);
+function _in_array() { in_array(5000,$GLOBALS['array']); } nb::benchmark('_in_array',1000);
+function _in_hash() { isset($GLOBALS['hash'][5000]); } nb::benchmark('_in_hash',1000);
 nb::benchmark(); exit;
 
 #function __f1(&$ar) { return; foreach ($ar as $v) { 1; } }
 #function __f2($ar) { return; foreach ($ar as $v) { 1; } }
-$array = array_fill(0,100000,"a");
 #if (function_exists('__f1')) { function _f1() { __f1($array); } nb::benchmark('_f1'); }
 #if (function_exists('__f2')) { function _f2() { __f2($array); } nb::benchmark('_f2'); }
 $fct = 'is_scalar';
index 327e7a27665ba1387f32c46599f81d57142da17b..b1abb3f152b9a5033841e75507dca7ed9d1651e2 100644 (file)
@@ -9,7 +9,8 @@
 require_once(dirname(__FILE__).'/nb.php');
 require_once(dirname(__FILE__).'/out.php');
 require_once(dirname(__FILE__).'/db/table.php');
-require_once(dirname(__FILE__).'/db/types.php');
+$DB_TYPES = array();
+# NB 29.03.16 require_once(dirname(__FILE__).'/db/types.php');
 
 class Db extends nb {
 
@@ -27,10 +28,10 @@ class Db extends nb {
   public $title;
   public $name;
   public $type;
-  public $tables = array();
+  public $tables;
 
   # Objects
-  public $table;
+# NB 28.03.16   public $table;
 
   # Web
   public $dbs; // others databases keys
@@ -39,27 +40,43 @@ class Db extends nb {
   public $extras;
   public $formats = array( 'table','div','csv','xml','json','yaml' );
   public $limits = array('10','20','50','100','500','1000');
-  public $help_criterias = array(
-    ' * or % for wildcar',
-    ' ! to negate',
-    ' ~ for regex',
-    ' combine criterias with OR/AND',
-  );
+  const help_criterias = '
+     * or % for wildcar
+     ! to negate
+     ~ for regex
+     combine criterias with OR/AND
+  ';
 
-  function __construct($db = '') {
+  function __construct($opt = '') {
 
     # Args
-    $db = is_scalar($db) ? array('pdo' => $db) : $db;
-    if (is_array($db)) {
-      foreach ($db as $k=>$v) $this->$k = $v;
+    $opt = is_scalar($opt) ? array('pdo' => $opt) : $opt;
+
+    # Tables - We dont want to affect this->tables
+    $tables = array();
+    if (isset($opt['tables'])) {
+      $tables = $opt['tables'];
+      unset($opt['tables']);
     }
 
+    # Args
+    foreach ($opt as $k=>$v) $this->$k = $v;
+
     #$this->formats += array_keys(out::$types);
     foreach(out::$types as $t=>$v) if (!in_array($t,$this->formats)) $this->formats[] = $t;
 
     # Pdo
-    return $this->connect();
+    $this->connect();
+
+    # Tables - Add missing infos
+    if (!empty($tables)) {
+      foreach (array_values($this->tables()) as $name=>$t) {
+        if (empty($tables[$name])) continue;
+        foreach($tables[$name] as $k=>$v) $t->$k = $v;
+      }
+    }
 
+    return true;
   }
 
        function connect($pdo=null) {
@@ -68,33 +85,28 @@ class Db extends nb {
     if (empty($this->pdo) and $this->type) $this->pdo = $this->type.':';
     if (empty($this->type)) $this->type = strtolower(preg_replace('/^([^:]+):.*$/','\1',$this->pdo));
 
-    # Title
-    if (empty($this->title)) $this->title = prettyText($this->name);
-
-    # Name
-    if (empty($this->name) and preg_match('/(?:sqlite:(?:.*\/)?|dbname=)([^;\.]+)/',$this->pdo,$m)) {
-      $this->name = $m[1];
-    }
-
     # User
     #preg_match_all('/[:;](user|username|password)=([^;]*)/',$this->pdo,$m); bye($m);
+    if( !$this->type ) return false;
+    if ($this->type('use_path')) {
+      $this->name = preg_replace('/^\w+:/','',$this->pdo);
 
-    # Params
-    if (preg_match_all("/[:;](\w+)=([^;]+)/",$this->pdo,$m,PREG_SET_ORDER)) {
-      #array_shift($m);
-      foreach ($m as $param) {
-        $k = $param[1]; 
-        if (!empty($this->$k)) continue;
-        $this->$k = $param[2];
-      }
-      #$this->bye($m);
-    }
-    #$this->bye($this->pdo);
+    } else {
 
-    if ($this->type == 'sqlite') {
-      $this->host = preg_replace('/^\w+:/','',$this->pdo);
+      # Extract args from pdo
+      if (preg_match_all("/[:;](\w+)=([^;]+)/",$this->pdo,$m,PREG_SET_ORDER)) {
+        #array_shift($m);
+        foreach ($m as $param) {
+          $k = $param[1]; 
+          if ($k == 'dbname') $k = 'name';
+          if (!empty($this->$k)) continue;
+          $this->$k = $param[2];
+        }
+        #$this->bye($m);
+      }
+      #$this->bye($this->pdo);
 
-    } else {
+      # Add args to pdo
       foreach (array(
         'host' => 'host',
         'port' => 'port',
@@ -107,64 +119,44 @@ class Db extends nb {
         $this->pdo = preg_replace("/\b$v=[^;]*(;|$)/","",$this->pdo);
         $this->pdo .= (preg_match('/[:;]$/',$this->pdo) ? '' : ';') . "$v=".$this->$k;
       }
+
     }
-    #self::bye(">>".$this->pdo);
+
+    # Title
+    if (empty($this->title)) $this->title = prettyText($this->name);
 
     # Pdo
     if (empty($this->pdo)) return false;
 
     # Type
-    if (!in_array($this->type,array(
-      'sqlite',
-      'mysql',
-      'pgsql',
-    ))) $this->bye("unknow type = `".$this->type."`");
+    if (!$this->type(null)) $this->bye("unknow type = `".$this->type."`");
 
     # Connect
-    if (preg_match('/^sqlite:(.*)$/',$this->pdo,$m) and !is_readable($m[1])) {
-      $this->bye("Can't connect to database `".$m[1]."` type=$this->type",false);
+# NB 28.03.16     if (preg_match('/^sqlite:(.*)$/',$this->pdo,$m) and !is_readable($m[1])) {
+# NB 28.03.16       $this->bye("Can't connect to database `".$m[1]."` type=$this->type",false);
+    if ($this->type('use_path') and !is_readable($this->name)) {
+      $this->bye("Can't read database file `".$this->name."` type=`$this->type`",false);
 
     } else {
       $this->conn = new PDO($this->pdo,$this->user,$this->password,$this->options);
 
-      if ($this->type == 'pgsql') {
-        if (isset($this->password)) $this->pdo = preg_replace('/\bpassword=([^;]+;?)/','',$this->pdo).'';
-      }
       if (isset($this->pdo_error)) $this->conn->setAttribute(PDO::ATTR_ERRMODE, $this->pdo_error);
     }
 
     if (empty($this->conn)) return false;
 
     # Create functions
-    if ($this->type == 'sqlite') {
-
-      $this->conn->sqliteCreateFunction('ip2int', function ($value) { return ip2long($value); });
-      $this->conn->sqliteCreateFunction('concat', function ($v1,$v2) { return $v1.$v2; });
-
-      $this->conn->sqliteCreateFunction('regexp',
-        function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS') {
-          if (isset($pattern, $data) === true) {
-              return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
-          }
-          return null;
-        }
-      );
-
-      $this->conn->sqliteCreateFunction('to_char',
-        function ($value,$format) {
-          $replace = array(
-              'YYYY' => '%Y',
-              'MM' => '%m',
-              'WW' => '%W',
-              'DD' => '%d',
-          );
-          $format = str_replace(array_keys($replace),array_values($replace),$format);
-          return strftime($format,strtotime($value));
+    if ($this->type('sqliteCreateFunction')) {
+      foreach ($this->type('sqliteCreateFunction') as $name => $fct) {
+        if (is_array($fct)) {
+          $this->conn->sqliteCreateFunction($name,$fct[0],$fct[1]);
+        } else {
+          $this->conn->sqliteCreateFunction($name,$fct);
         }
-      ,2);
-
+      }
     }
 
+    # Bye
     return empty($this->conn) ? false : true;
   }
 
@@ -252,106 +244,81 @@ class Db extends nb {
     return $this->conn->quote($v);
   }
 
-  function table($name) {
-    $opt = array('db' => $this);
+  function table($name,$opt=array()) {
+    if (empty($opt['db'])) $opt['db'] = $this;
 # NB 28.03.16     if (sset($this->tables) and array_key_exists($name,$this->tables)) {
 # NB 28.03.16       foreach ($this->tables[$name] as $k=>$v) { $opt[$k] = $v; }
 # NB 28.03.16     }
     return new Table($name,$opt);
-    #return new Table($name,array_merge($opt));
   }
 
-  public function config() {
+  public function localFile() {
 
-    $config = $this->type('config',true);
+    $config = $this->type('localFile',true);
 
     $config[1] = str_replace('<NAME>',$this->name,$config[1]);
 
     if (!file_exists($config[0])) return array();
-    $conf = file_get_contents($config[0]);
 
     $return = array();
-    foreach (explode("\n",$conf) as $line) {
+    foreach (explode("\n",file_get_contents($config[0])) as $line) {
 #bye($line);
       if (!preg_match('/'.($config[1]).'/',$line,$m)) continue;
       foreach ($m as $k=>$v) if (preg_match('/^\d+$/',$k)) unset($m[$k]);
       $return = array_replace_recursive($return,$m);
     }
 
+#debug(self::ar_map('$a == null ? "" : $a',$return));
 #debug($return);
     return $return;
   }
 
-  public function type($key=false,$die=false) {
-    #if (!isset($DB_TYPES[$key][$this->type])) return;
+  public function type($key=null,$die=false) {
     global $DB_TYPES;
 
-    if ($key === false) {
-      $types = array();
-
-      foreach ($DB_TYPES as $k=>$v) {
-        if (!isset($v[$this->type])) continue;
-        $types[$k] = $v[$this->type];
-        #$types[] = array( $k => $v[$this->type] );
-      }
-#bye($types);
-      return $types;
-
+    static $require = array();
+    if (empty($require[$this->type])) {
+      require_once(dirname(__FILE__).'/db/types/'.$this->type.'.php');
+      $require[$this->type] = 1;
     }
 
-    if (
-      !isset($DB_TYPES[$key])
-      or !isset($DB_TYPES[$key][$this->type])
-      or empty($DB_TYPES[$key][$this->type])
-    ) {
-      #self::bye("db.type(): Unknow key `$key` for type `".$this->type."`".print_r($DB_TYPES,1));
-      #nb::msg(">>>".$DB_TYPES[$key][$this->type]);
-      if ($die) self::bye("db.type(): Unknow key `$key` for type `".$this->type."`");
+    if ($key === null) return $DB_TYPES[$this->type];
+
+    if (empty($DB_TYPES[$this->type][$key])) {
+      if ($die) self::bye("db.type(): Unknow key `$key` for type `".$this->type."`");#.' - '.print_r($DB_TYPES,true));
       return;
     }
 
-    return $DB_TYPES[$key][$this->type];
+    return $DB_TYPES[$this->type][$key];
   }
 
-  public function tables($return_hash=false) {
-    if (isset($this->_tables) and $this->_tables) return ($return_hash ? $this->tables : $this->_tables);
-    if (!isset($this->_tables)) $this->_tables = array();
-
-    $sql = $this->type('tables',true);
-
-    $rows = $this->conn->query($sql,PDO::FETCH_ASSOC);
-    foreach ($rows as $row) {
+  public function tables() {
+    if (isset($this->tables)) return $this->tables;
+    $this->tables = array();
+    foreach ($this->conn->query($this->type('tables',true),PDO::FETCH_ASSOC) as $row) {
       $name = current($row);
-      $this->_tables[] = $name;
-
-      if (!isset($this->tables[$name])) $this->tables[$name] = array();
-      foreach ($row as $k => $v) {
-        $this->tables[$name][$k] = $v;
-      }
+      $this->tables[$name] = $this->table($name,$row);
+#bye($this->tables);
     }
-    #bye($this->query("SELECT DATABASE()"));
-    #bye($this->_tables);
-    #bye($rows);
-
-    if ($return_hash) return $this->tables;
-    return $this->_tables;
-
+#bye($this->tables);
+    #return array_values($this->tables);
+    return $this->tables;
   }
 
-  public function rowCount($st) {
-    if (!$st) return null;
-    if ($this->type != 'sqlite') return $st->rowCount();
-    $sql = $st->queryString;
-    return $this->conn->query("SELECT count(*) FROM ($sql) count",PDO::FETCH_COLUMN,0)->fetch();
-  }
+# NB 28.03.16   public function rowCount($st) {
+# NB 28.03.16     if (!$st) return null;
+# NB 28.03.16     if ($this->type != 'sqlite') return $st->rowCount();
+# NB 28.03.16     $sql = $st->queryString;
+# NB 28.03.16     return $this->conn->query("SELECT count(*) FROM ($sql) count",PDO::FETCH_COLUMN,0)->fetch();
+# NB 28.03.16   }
 
   function help($tables=null) {
     if (!empty($_SERVER['DOCUMENT_ROOT'])) header('Content-type: text/plain');
 
-    if ($tables === null) $tables = $this->tables();
+    if ($tables === null) $tables = array_keys($this->tables());
     $tables = join('',ar_map('"  ".$a."\n"',$tables));
 
-    $criterias = join('',ar_map('"  ".$a."\n"',$this->help_criterias));
+    $criterias = join('',ar_map('"  ".trim($a)."\n"',explode("\n",self::help_criterias)));
 
     return <<<EOF
 Criterias:
@@ -501,8 +468,8 @@ EOF;
           $return = true;
 
         } elseif ($action == 'db.tables' or $action == 'tables') {
-          foreach ($this->tables() as $name) {
-            $rows[] = $this->table($name)->infos();
+          foreach ($this->tables() as $t) {
+            $rows[] = $t->infos();
           }
           $return = $this->out2($rows);
 
@@ -517,7 +484,7 @@ EOF;
         } elseif (preg_match('/^db\.(\w+)/',$action,$m)) {
           $meth = $m[1];
           $rows = $this->$meth();
-          if ($rows) $return = $this->out2($rows,self::is_hash($rows) ? true : array($meth));
+          if ($rows) $return = $this->out2($rows,self::is_hash($rows) ? array_keys($rows) : array($meth));
           $return = true;
 
         } elseif($table) {
@@ -563,7 +530,6 @@ EOF;
           and $k != '_import'
         ) continue;
 
-        ##die 'zaza';
         $import = is_array($v) ? $v : explode(',',$v);
         #debug($import);
         foreach ($import as $v) {
@@ -630,14 +596,14 @@ EOF;
 
     $Db->__construct($db);
 
-    if (empty($Db->pdo)) $Db->bye("No pdo for db: `".$Db->p('db')."`",false);
+    if (empty($Db->pdo)) $Db->bye("No pdo for db: `".$Db->p('db')."`");
 
     /*
       Table
     */
     if (empty($Db)) return false;
     if (!$Db->p('table') and isset($Db->default_table)) $Db->pset('table',$Db->default_table);
-    if (!$Db->p('table') and ($v = $Db->tables())) $Db->pset('table',$Db->ar_first($v));
+    if (!$Db->p('table') and ($v = array_keys($Db->tables()))) $Db->pset('table',$Db->ar_first($v));
 
     # NB 10.01.16 $Table = new table($Db->p('table'),array('db' => $Db));
     if ($Db->p('table')) $Table = $Db->table($Db->p('table'));
@@ -669,7 +635,6 @@ EOF;
       #."-- Host     : ".$this->host."\n"
     ;
     foreach ($this->tables() as $t) {
-      $t = $this->table($t);
       if ($insert) echo "\n-- Table: ".$t->name."\n";
       echo rtrim($t->sql(),';').';'.NB_EOL;
       if ($insert) $t->rows();
@@ -678,6 +643,18 @@ EOF;
     return $r;
   }
 
+  public function infos() {
+    return array(
+      array('key'=>'host','val'=>$this->host),
+      array('key'=>'port','val'=>$this->port),
+      array('key'=>'name','val'=>$this->name),
+      array('key'=>'user','val'=>$this->user),
+      #array('key'=>'tables','val'=>count($this->tables())),
+      #array('key'=>'dbs','val'=>count($this->dbs)),
+      array('key'=>'tables','val'=>join(' ',array_keys($this->tables()))),
+      array('key'=>'dbs','val'=>join(' ',array_values($this->dbs))),
+    );
+  }
 } # < Class
 
 ?>
index 485e8e89a93f9bc0f91e28fbc682851a7998210b..a2f4f45c0ab00042e9201a4d335c202c9bc3c19f 100755 (executable)
@@ -18,6 +18,7 @@ if (preg_match('/^(\w+)\.(.*?)$/',Db::p('table'),$m)) {
   Db::pset('db',$m[1]);
   Db::pset('table',$m[2]);
 }
+#bye(Db::conf_dbs(array( Db::ROOT_DIR.'/etc/dbs.yaml','/etc/dbs.yaml' )));
 #$conf = Db::conf_dbs(array( Db::ROOT_DIR.'/etc/dbs.yaml','/etc/dbs.yaml' )); Db::init($conf);
 Db::init(array( Db::ROOT_DIR.'/etc/dbs.yaml','/etc/dbs.yaml' ));
 
index 04233f70d9c15c82cbbb1fe0b61fe4df01fdd86f..f96bd3da96c47695c4920f2d68d5d3e8d6ee825d 100644 (file)
@@ -6,16 +6,6 @@ require_once(dirname(__FILE__).'/../out.php');
 define('TABLE_INDENT',NB_EOL ? "\t" : "");
 define('TABLE_CSV_SEP',nb::p('sep') ? nb::p('sep') : "\t");
 
-if (!defined('DB_HTML_FORM_BUTTONS')) define('DB_HTML_FORM_BUTTONS',''
-  #.'<input type="button" class="button" value="Add" onclick="this.setAttribute(\'type\',\'submit\');this.setAttribute(\'name\',\'edit\')?1:1"/>'
-  #.'<input type="button" class="button" value="Add" onclick="this.setAttribute(\'name\',\'edit\');this.parentElement.submit()?0:0"/>'
-  #.'<input type="button" class="button" onclick="return nb.form_clear(this.parentElement)" value="X"/>'
-// NB 04.08.15   .'<a class="button form_clear" href="#" onclick="nb.form_clear(this.parentElement)?0:0">X</a>'
-  .'<span class="buttons">'
-  .'<input type="submit" class="button submit" value="GO"/>'
-  .'<input type="button" class="button table_add" value="Add" onclick="window.location = \'?action=edit&amp;table=\'+$(\'#table\').val()"/>'
-  .'</span>'
-);
 #if (!defined('DB_HTML_BUTTON_SUBMIT')) define('DB_HTML_BUTTON_SUBMIT','<input type="submit" class="button" value="GO"/>');
 #if (!defined('DB_HTML_BUTTON_ADD'))    define('DB_HTML_BUTTON_ADD','<a class="button" href="?" onclick="nb.form_clear(this.parentElement) ? 0: 0">Add</a>');
 #if (!defined('DB_HTML_BUTTON_ADD'))    define('DB_HTML_BUTTON_ADD','<input type="submit" class="button" value="Add" onclick="this.setAttribute(\'name\',\'edit\')?0:0"/>');
@@ -36,34 +26,34 @@ Class Table extends nb {
   public $created;
 
   # hidden, sort, ... fields
-  public $params = array( 'table', 'limit', 'debug', 'action');
-  public $order_by = null;
+  public static $params = array( 'table', 'limit', 'debug', 'action');
 
+  public $orderby = null;
   public $fields;
-  public $db;
 
   function __construct($name,$opt=array()) {
 
     if (!is_scalar($name)) {
       $opt = $name;
-      $name = null;
+      $name = $opt['name'];
     }
-
-    foreach ($opt as $k => $v) { $this->$k = $v; }
     #unset($opt['db']); bye($opt);
 
     // Connection
     if (isset($opt['db'])) {
-      $this->db = is_object($opt['db']) ? $opt['db'] : new Db($opt['db']);
+      $this->db(is_object($opt['db']) ? $opt['db'] : new Db($opt['db']));
     } else {
-      $this->db = new Db();
+      $this->db(new Db());
     }
 
+    unset($opt['db']);
+    foreach ($opt as $k => $v) { $this->$k = $v; }
+
     // Name, could be a select
     if (stripos($name,'SELECT ')===0) {
       #$temp = '_'.substr(md5($name),0,6);
       $temp = DB_TABLE_QUERY_NAME;
-      $this->db->conn->query("CREATE TEMPORARY TABLE $temp AS $name");
+      $this->db()->conn->query("CREATE TEMPORARY TABLE $temp AS $name");
       $name = $temp;
     } elseif (preg_match('/\b(\.import|LOAD DATA|COPY|INSERT|REPLACE|DELETE|TRUNCATE|CREATE|DROP|ALERT)\b/',$name)) {
       bye("Query not Allowed !");
@@ -78,26 +68,34 @@ Class Table extends nb {
     } else if (isset($opt['extras'])) {
       $this->add_extras($opt['extras']);
 
-    } elseif (
-      isset($this->db->extras)
-      and isset($this->db->extras[$this->name])
+    } elseif ($this->db()
+      and isset($this->db()->extras)
+      and isset($this->db()->extras[$this->name])
     ) {
-      $this->add_extras($this->db->extras[$this->name]);
+      $this->add_extras($this->db()->extras[$this->name]);
 
     }
 
     // Sort
-# NB 10.01.16     if (
-# NB 10.01.16       isset($this->db->sort)
-# NB 10.01.16       and isset($this->db->sort[$this->name])
-# NB 10.01.16     ) $this->db->pset('orderby',$this->db->sort[$this->name]);
-    if ($this->order_by) $this->pset('orderby',$this->order_by);
+    if ($this->orderby) $this->pset('orderby',$this->orderby);
 
     return $this->fields();
   }
 
   /*
-   * Function db.sql
+   * Function db
+   *
+   * return the db object or init it
+   *
+   */
+  public function db($set=null) {
+    static $db = null;
+    if ($set !== null) $db = $set;
+    return $db;
+  }
+
+  /*
+   * Function sql
    *
    * return the sql to create the table
    *
@@ -110,8 +108,8 @@ Class Table extends nb {
       return $this->sql;
     }
 
-    $sql = str_replace('<NAME>',$this->name,$this->db->type('table.sql',true));
-    $this->sql = $this->db->row($sql);
+    $sql = str_replace('<NAME>',$this->name,$this->db()->type('table.sql',true));
+    $this->sql = $this->db()->row($sql);
 
     # Noise before CREATE from mysql
     $this->sql = preg_replace("/^\w+\s+(CREATE)/i",'$1',$this->sql);
@@ -143,9 +141,9 @@ Class Table extends nb {
     if (!isset($this->fields)) {
 
       $this->fields = array();
-      $conf = str_replace('<NAME>',$this->name,$this->db->type('table.fields',true));
+      $conf = str_replace('<NAME>',$this->name,$this->db()->type('table.fields',true));
       if (is_scalar($conf)) $conf = array('sql'=>$conf);
-      $rows = $this->db->conn->query($conf['sql']);
+      $rows = $this->db()->conn->query($conf['sql']);
       $rows->setFetchMode(PDO::FETCH_ASSOC);
 
       foreach ($rows as $row) {
@@ -169,24 +167,15 @@ Class Table extends nb {
           'default'       => (isset($row['default']) ? $row['default'] : null),
           'key'           => (preg_match('/^(f.*|no|0)?\s*$/i',$row['key']) ? 0 : 1),
           'null'          => (preg_match('/^(f.*|no|0)?\s*$/i',$row['null']) ? 0 : 1),
-          #'key'           => (isset($row['key']) ? $row['key'] : 0),
           'extra'         => null, # !!! nothing todo with class variable $extras, this info from the sql server
           'autoincrement' => (isset($row['autoincrement']) ? $row['autoincrement'] : 0),
         );
 
-        # sqlite autoincrement only in sql
-        if ($this->db->type == 'sqlite'
-          and preg_match('/[\(,]'.$row['name'].' [^\),]+ AUTOINCREMENT/',$this->sql())
-        ) {
-          $field['autoincrement'] = 1;
-
-        }
-
         $this->fields[$field['name']] = new Field($field);
 
       }
 
-      if (empty($this->fields)) bye("Table `".$this->name."` does not exists into database ".$this->db->name."!");
+      if (empty($this->fields)) bye("Table `".$this->name."` does not exists into database ".$this->db()->name."!");
 
     } # < $this->fields
 
@@ -252,7 +241,7 @@ Class Table extends nb {
 # NB 28.03.16     $this->sql = $sql;
 
     $this->debug($sql,1);
-    $st = $this->db->conn->prepare($sql);
+    $st = $this->db()->conn->prepare($sql);
     $st->execute();
 
     echo '<form class="db edit" method="post" action="?">'.NB_EOL;
@@ -292,7 +281,7 @@ Class Table extends nb {
     $params = array();
     $fields = ($this->p('action') == 'delete') ? array() : $this->fields();
 
-    foreach (array_merge( $this->params, array_keys($fields) ) as $f) {
+    foreach (array_merge( self::$params, array_keys($fields) ) as $f) {
 
       if (strcmp($this->p($f,''),'')==0) continue;
       $params[$f] = $this->p($f);
@@ -426,7 +415,7 @@ Class Table extends nb {
       // Regex
       if (strpos($v,'~')===0) {
         $v = substr($v,1);
-        $v = $this->db->quote($v);
+        $v = $this->db()->quote($v);
         $equal = ' '.($not ? 'NOT ' : '').'REGEXP ';
 
       // Text
@@ -440,7 +429,7 @@ Class Table extends nb {
         // * -> %
         $v = str_replace('*','%',$v);
 
-        $v = $this->db->quote($v);
+        $v = $this->db()->quote($v);
         $equal = ' '.($not ? 'NOT ' : '').'LIKE ';
 
       // Others
@@ -452,7 +441,7 @@ Class Table extends nb {
 
         // Date, Time
         } else {
-          $v = $this->db->quote($v);
+          $v = $this->db()->quote($v);
 
         }
         $equal = $not ? '<>' : '=';
@@ -460,13 +449,13 @@ Class Table extends nb {
       }
 
       if (preg_match('/(LIKE|REGEXP) ..$/',"$equal$v")) {
-        $k = "COALESCE($k,".$this->db->quote('').")";
+        $k = "COALESCE($k,".$this->db()->quote('').")";
       }
 
-      if ($this->db->type == 'mysql' and $field->extra) {
+      if ($this->db()->type == 'mysql' and $field->extra) {
         $having[] = "$k$equal$v";
 
-      } elseif ($this->db->type == 'pgsql' and $field->extra) {
+      } elseif ($this->db()->type == 'pgsql' and $field->extra) {
         $where[] = $this->extras[$k]."$equal$v";
 
       } else {
@@ -526,7 +515,7 @@ Class Table extends nb {
     // Select
     //
     $where = $this->where_criterias($this->p(),$this->p('op'));
-    $select_count = ( (false and $where and $this->db->type =='mysql') ? " SQL_CALC_FOUND_ROWS" : "");
+    $select_count = ( (false and $where and $this->db()->type =='mysql') ? " SQL_CALC_FOUND_ROWS" : "");
 
     $sql = "SELECT$select_count *" . $this->select_extras();
     $sql .= " FROM ".$this->sql_name();
@@ -546,7 +535,7 @@ Class Table extends nb {
     //
 # NB 28.03.16     $this->sql = $sql;
     $this->debug($sql,1);
-    $st = $this->db->conn->prepare($sql);
+    $st = $this->db()->conn->prepare($sql);
     $st->execute();
 
     if (!isset($opt['is_html'])) $opt['is_html'] = preg_match('/^(table|div)$/',$format)
@@ -564,7 +553,7 @@ Class Table extends nb {
     {
 
       if (!($out_conf = out::type($format))) $this->bye("Unknow format `$format`");
-      $this->params += array_values(out::$types);
+      self::$params += array_values(out::$types);
 
       if (empty($out_conf['enclose'])) $out_conf['enclose'] = array('','');
       debug('Using out module!',1);
@@ -623,19 +612,19 @@ Class Table extends nb {
         //
         if (!$where and !$limit) {
           debug("Table.rows(): Not using count(*)",1);
-          $query = $this->db->conn->query("SELECT $count");
+          $query = $this->db()->conn->query("SELECT $count");
 
         } elseif ($select_count) {
-          $query = $this->db->conn->query('SELECT FOUND_ROWS()');
+          $query = $this->db()->conn->query('SELECT FOUND_ROWS()');
 
         } elseif ($where) {
           $sql_count = $sql;
           $sql_count = preg_replace('/ (ORDER|LIMIT) .*?$/s','',$sql_count);
           $sql_count = preg_replace('/^SELECT .*FROM/s','SELECT count(*) FROM ',$sql_count);
-          $query = $this->db->conn->query($sql_count);
+          $query = $this->db()->conn->query($sql_count);
 
         } else {
-          $query = $this->db->conn->query('SELECT count(*) FROM '.$this->sql_name());
+          $query = $this->db()->conn->query('SELECT count(*) FROM '.$this->sql_name());
 
         }
 
@@ -730,7 +719,7 @@ Class Table extends nb {
     $this->_row_json = null;
     return '['.NB_EOL;
     return ''
-      #."// database: ".$this->db->name."\n"
+      #."// database: ".$this->db()->name."\n"
       #."// table: $this->name\n"
     .'['.NB_EOL;
   }
@@ -764,8 +753,8 @@ Class Table extends nb {
   public function rows_begin_xml() {
     return ''
       .'<?xml version="1.0" encoding="utf-8"?>'.NB_EOL #<?
-      #.'<database name="'.$this->db->name.'" table="'.$this->name.'" type="'.$this->db->type.'">'.NB_EOL
-      .'<rows name="'.$this->name.'" database="'.$this->db->name.'" database-type="'.$this->db->type.'">'.NB_EOL
+      #.'<database name="'.$this->db()->name.'" table="'.$this->name.'" type="'.$this->db()->type.'">'.NB_EOL
+      .'<rows name="'.$this->name.'" database="'.$this->db()->name.'" database-type="'.$this->db()->type.'">'.NB_EOL
     ;
   }
 
@@ -899,7 +888,7 @@ Class Table extends nb {
   }
 
   public function sql_name($value=null) {
-    return $this->db->sql_name($value === null ? $this->name : $value);
+    return $this->db()->sql_name($value === null ? $this->name : $value);
   }
 
   public function insert($hvalues) {
@@ -919,8 +908,8 @@ Class Table extends nb {
       .' VALUES (' . join(',',ar_map('":$a"',array_keys($fields))) . ')'
     ;
 
-    if (!($query = $this->db->conn->prepare($sql))) {
-      err('PDO::errorInfo(): ' .join(' ', $this->db->conn->errorInfo()) .NB_EOL);
+    if (!($query = $this->db()->conn->prepare($sql))) {
+      err('PDO::errorInfo(): ' .join(' ', $this->db()->conn->errorInfo()) .NB_EOL);
       return false;
     }
 
@@ -928,14 +917,14 @@ Class Table extends nb {
 
 #debug(array($sql,$values));
     if (!($execute = $query->execute())) {
-      err('PDO::errorInfo(): ' .join(' ', $this->db->conn->errorInfo()) .NB_EOL);
+      err('PDO::errorInfo(): ' .join(' ', $this->db()->conn->errorInfo()) .NB_EOL);
       return false;
     }
 
     return $execute;
 
-    return $this->db->exec($sql,$values);
-    return $this->db->exec($sql);
+    return $this->db()->exec($sql,$values);
+    return $this->db()->exec($sql);
   }
 
   public function update($hvalues,&$info=null) {
@@ -983,8 +972,8 @@ Class Table extends nb {
       .' WHERE ' . join(' AND ',$this->ar_map('"$a=:key_$a"',$keys))
     ;
 
-    if (!($query = $this->db->conn->prepare($sql))) {
-      err('PDO::errorInfo(): ' .join(' ', $this->db->conn->errorInfo()) .NB_EOL);
+    if (!($query = $this->db()->conn->prepare($sql))) {
+      err('PDO::errorInfo(): ' .join(' ', $this->db()->conn->errorInfo()) .NB_EOL);
       return false;
     }
      
@@ -1001,7 +990,7 @@ Class Table extends nb {
     #return $sql;
     #bye($sql);
     if (!($ex = $query->execute())) {
-      err('PDO::errorInfo(): ' .join(' ', $this->db->conn->errorInfo()) .NB_EOL);
+      err('PDO::errorInfo(): ' .join(' ', $this->db()->conn->errorInfo()) .NB_EOL);
       return false;
     }
 
@@ -1024,11 +1013,11 @@ Class Table extends nb {
 
     $sql = 'DELETE FROM ' . $this->sql_name() . $where;
     bye($sql);
-    return $this->db->exec($sql);
+    return $this->db()->exec($sql);
   }
 
-  public function out($v,$head=false) { return $this->db->out($v,$head); }
-  public function out2($v,$head=array()) { return $this->db->out2($v,$head); }
+  public function out($v,$head=false) { return $this->db()->out($v,$head); }
+  public function out2($v,$head=array()) { return $this->db()->out2($v,$head); }
 
   public function infos() {
     return 
@@ -1059,11 +1048,11 @@ Class Table extends nb {
     } elseif ($action == 'table.count') { return $this->out2($this->count(),'count');
 
     } elseif ($action == 'table.rows' or $action == 'rows') {
-      $this->db->print_header($this->p('format'));
+      $this->db()->print_header($this->p('format'));
       $this->rows(); return true;
 
-    } elseif ($action == 'table') {
-      return $this->out2($this->infos());
+    } elseif ($action == 'table.info') {
+      return $this->out2($this->info());
 
     } elseif ($action == 'table.delete' or $action == 'delete') {
       if (!$this->delete($this->p(),$e)) bye($e);
@@ -1149,40 +1138,37 @@ Class Table extends nb {
 
     }
 
-    $this->count = (int)$this->db->row($sql_count);
+    $this->count = (int)$this->db()->row($sql_count);
     return $this->count;
 
   }
 
   public static function err_sql($sql) {
-    $err = $this->db->conn->errorInfo();
+    $err = $this->db()->conn->errorInfo();
     $err[] = $sql;
     self::bye(join(' | ',$err));
   }
 
   public function html_menu() {
 
-    $r = '<form class="db menu" method="get" action="?">'.NB_EOL;
+    $r = '<form class="menu" method="get" action="?">'.NB_EOL;
 
     // Criterias
-    if (!empty($this)) {
-      $r .= '<div class="criterias">';
-      foreach ( array_keys($this->fields()) as $k ) {
+    $r .= '<div class="criterias">';
+    foreach ( array_keys($this->fields()) as $k ) {
 
-        $v = $this->p($k);
+      $v = $this->p($k);
 
-        $r .= ''
-          .'<span class="label '.$k.'">'
-          . '<label>'.prettyText($k)
-          .'</label>'
-          . '<input type="text" id="'.$k.'" name="'.$k.'" value="'.$v.'" />'
-          .'</span>'
-        ;
+      $r .= ''
+        .'<span class="label '.$k.'">'
+        . '<label>'.prettyText($k)
+        .'</label>'
+        . '<input type="text" id="'.$k.'" name="'.$k.'" value="'.$v.'" />'
+        .'</span>'
+      ;
 
-      }
-      $r .= '</div>';
-      #$r .= '<span class=""></span>';
     }
+    $r .= '</div>';
 
     //
     // Hiddens
@@ -1202,7 +1188,7 @@ Class Table extends nb {
 
     // Tables
     $r .= '<span class="label">';
-    $r .= '<label for="table">Tables</label>'.html_select_array(array_keys($this->db->tables()),array(
+    $r .= '<label for="table">Tables</label>'.html_select_array(array_keys($this->db()->tables()),array(
       'html'       => 'class="tables" name="table" id="table"',
       'selected'   => $this->p('table'),
       'prettyText' => true,
@@ -1215,7 +1201,7 @@ Class Table extends nb {
   #$criteria[] = html_select_array(ar_map('array($a == "html" ? "" : $a,strtoupper($a))',$this->formats));
 # NB 01.03.16     $r .= '<label for="format">Format</label>'.html_select_array(array(
 # NB 01.03.16       'table','div','csv','xml','json','yaml'
-    $r .= '<label for="format">Format</label>'.html_select_array($this->db->formats,array(
+    $r .= '<label for="format">Format</label>'.html_select_array($this->db()->formats,array(
       'html'       => 'class="format" name="format" id="format"',
       'selected'   => $this->p('format'),
       'prettyText' => true,
@@ -1223,9 +1209,9 @@ Class Table extends nb {
     $r .= '</span>';
 
     // Limit
-    if (!empty($this->db->limits)) {
+    if (!empty($this->db()->limits)) {
       $r .= '<span class="label">';
-      $r .= '<label for="limit">Limit</label>'.html_select_array($this->db->limits,array(
+      $r .= '<label for="limit">Limit</label>'.html_select_array($this->db()->limits,array(
         'html'       => 'class="limit" name="limit" id="limit"',
         'selected'   => $this->p('limit'),
         'prettyText' => true,
@@ -1234,9 +1220,9 @@ Class Table extends nb {
     }
 
     // Dbs
-    if (!empty($this->db->dbs) and count($this->db->dbs)>1) {
+    if (!empty($this->db()->dbs) and count($this->db()->dbs)>1) {
       $r .= '<span class="label">';
-      $r .= '<label for="db">Db</label>'.html_select_array($this->db->dbs,array(
+      $r .= '<label for="db">Db</label>'.html_select_array($this->db()->dbs,array(
         'html'       => 'class="dbs" onchange="document.location=\''.preg_replace('/\?.*$/','',$_SERVER['REQUEST_URI']).'?db=\'+this.value"',
         'selected'   => $this->name,
         'prettyText' => true,
@@ -1244,9 +1230,6 @@ Class Table extends nb {
       $r .= '</span>';
     }
 
-    // Buttons
-    $r .= DB_HTML_FORM_BUTTONS;
-
     $r .= '</div>';
 
     ///
@@ -1258,7 +1241,7 @@ Class Table extends nb {
 
   public function __wakeup() {
     global $Db;
-    if (empty($this->db) and !empty($Db)) $this->db = $Db;
+    $this->db($Db);
   }
 
   public function __sleep() {
@@ -1272,7 +1255,7 @@ Class Table extends nb {
 # NB 28.03.16       'replace',
       'extras',
       #'params',
-      'order_by',
+      'orderby',
       'count',
       'engine',
       'created',
@@ -1291,7 +1274,6 @@ Class Table extends nb {
     #return serialize($this->fields());
     #$this = $o;
     #return($o->sql_name());
-    #var_export($o->db);
     #debug($o->sql_name());
     return var_export($o,true);
   }
index e31873e4c3a74b2a674896630ff0db33431176f9..6edb27ea6b47b2a2fc3e75d087d99dfb46282b6e 100644 (file)
@@ -1,9 +1,39 @@
 <?php
+require_once(dirname(__FILE__).'/../nb.php');
 $DB_TYPES = array(
 
-  'config' => array(
+  'use_path' => array(
+    'sqlite' => true,
+  ),
+
+  'sqliteCreateFunction' => array(
+    'sqlite' => array(
+      'ip2int' => function ($value) { return ip2long($value); },
+      'concat' => function ($v1,$v2) { return $v1.$v2; },
+      'regexp' => function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS') {
+          if (isset($pattern, $data) === true) {
+            return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
+          }
+          return null;
+        }
+      ,
+      'to_char' => array(function ($value,$format) {
+          $replace = array(
+              'YYYY' => '%Y',
+              'MM' => '%m',
+              'WW' => '%W',
+              'DD' => '%d',
+          );
+          $format = str_replace(array_keys($replace),array_values($replace),$format);
+          return strftime($format,strtotime($value));
+        }
+      ,2),
+    ),
+  ),
+
+  'localFile' => array(
     # hostname:port:database:username:password
-    'sqlite' => array(getenv('HOME').'/'.'.db.sqlite', '^(?:user(?:name)?=(?P<user>\S+)|password=(?P<password>\S+))'),
+    'sqlite' => array(getenv('HOME').'/'.'.sqlite', '^(?:user(?:name)?=(?P<user>\S+)|password=(?P<password>\S+))'),
     'mysql' => array(getenv('HOME').'/'.'.my.cnf', '^(?:user(?:name)?=(?P<user>\S+)|password=(?P<password>\S+))'),
     'pgsql' => array(getenv('HOME').'/'.'.pgpass', '^[^:]+:[^:]+:<NAME>:(?P<user>[^:]+):(?<password>[^:]+)'),
     #'sqlite' => array($_SERVER['HOME'].'/'.'.db.pass', '^<NAME>:(?P<user>[^:]*):(?<password>[^:]*)'),
@@ -123,4 +153,15 @@ FROM pg_catalog.pg_class c WHERE c.relname = '<NAME>' AND pg_catalog.pg_table_is
   ),
 );
 #die($DB_TYPES['tables']['mysql']);
+return;
+if (empty($argv) or count($argv)<2) return;
+$new = array();
+$filter = $argv[1];
+foreach ($DB_TYPES as $key => $types) {
+  foreach ($types as $type => $val) {
+    if($filter and $filter!=$type) continue;
+    $new[$type][$key] = $val;
+  }
+}
+var_export($new);
 ?>
diff --git a/lib/php/db/types/mysql.php b/lib/php/db/types/mysql.php
new file mode 100644 (file)
index 0000000..e202f67
--- /dev/null
@@ -0,0 +1,19 @@
+<?php
+$DB_TYPES['mysql'] = array (
+
+'localFile' => array (getenv('HOME').'/.my.cnf','^(?:user(?:name)?=(?P<user>\\S+)|password=(?P<password>\\S+))'),
+
+'table.sql' => 'SHOW CREATE TABLE `<NAME>`',
+
+'tables' => 'SELECT TABLE_NAME as name,LOWER(IF(TABLE_TYPE=\'BASE TABLE\',\'TABLE\',TABLE_TYPE)) as type,ENGINE as engine,CREATE_TIME as created FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE()',
+
+'table.fields' => array (
+  'sql' => 'SHOW COLUMNS FROM `<NAME>`',
+  'fct' => create_function('&$r',join('',array(
+    '$r["autoincrement"] = $r["extra"] == "auto_increment" ? 1 : 0;',
+    '$r["name"] = $r["field"];',
+  ))),
+),
+
+);
+?>
diff --git a/lib/php/db/types/pgsql.php b/lib/php/db/types/pgsql.php
new file mode 100644 (file)
index 0000000..2d17155
--- /dev/null
@@ -0,0 +1,84 @@
+<?php
+$DB_TYPES['pgsql'] = array (
+'localFile' => array (getenv('HOME').'/.pgpass','^[^:]+:[^:]+:<NAME>:(?P<user>[^:]+):(?<password>[^:]+)'),
+
+'tables' => 'SELECT table_name as name,LOWER(CASE table_type WHEN \'BASE TABLE\' THEN \'TABLE\' ELSE table_type END) as type,table_type FROM information_schema.tables WHERE table_type in(\'BASE TABLE\',\'VIEW\') AND table_schema NOT IN (\'pg_catalog\', \'information_schema\')',
+
+'table.fields' => array (
+  'fct' => create_function('&$r',join('',array(
+    'if (!isset($r["pg_default"])) return;',
+    'if (preg_match("/^nextval\(/",$r["pg_default"])) { $r["autoincrement"] = 1; }',
+    'elseif (preg_match("/^\'\'/",$r["pg_default"])) { $r["default"] = ""; }',
+    'else { $r["default"] = $r["pg_default"]; }',
+  ))),
+  'sql' => 'SELECT
+a.attname AS name,
+pg_catalog.format_type(a.atttypid, a.atttypmod) AS type,
+CASE a.attnotnull WHEN \'f\' then 1 ELSE 0 END AS null,
+(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) AS pg_default,
+(SELECT 1 FROM pg_index i WHERE a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) AND i.indrelid = \'<NAME>\'::regclass AND i.indisprimary) as key
+FROM pg_catalog.pg_attribute a
+WHERE a.attrelid = (
+  SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname=\'<NAME>\' AND pg_catalog.pg_table_is_visible(c.oid)
+  )
+  AND a.attnum > 0 AND NOT a.attisdropped
+ORDER BY a.attnum',
+
+'table.sql' => '
+SELECT CASE c.relkind::char WHEN \'r\' THEN (
+SELECT
+  \'CREATE TABLE \'||sql.table||\'(
+ \'
+    ||array_to_string(array_agg(sql),\',
+ \')
+  ||\'
+)\' as sql
+FROM (
+  (
+    SELECT -- FIELDS
+      c.oid AS id
+      ,c.relname as table
+      ,9 as prio
+      ,\'\'
+        || f.attname
+        || \' \' || pg_catalog.format_type(f.atttypid,f.atttypmod)
+        ||CASE WHEN f.attnotnull THEN \' NOT NULL\' ELSE \'\' END
+        ||CASE WHEN f.atthasdef = \'t\' AND d.adsrc !=\'\'THEN \' DEFAULT \'||d.adsrc ELSE \'\' END
+      AS sql
+    FROM pg_attribute f
+        JOIN pg_class c ON c.oid = f.attrelid
+        LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
+    WHERE c.relkind::char IN ( \'r\' ) --, \'v\' )
+    AND f.attnum > 0
+    ORDER BY f.attnum
+  )  UNION (
+    SELECT -- CONSTRAINTS
+        c.oid as id
+        ,c.relname as table
+        ,0 as prio
+        ,CASE
+          WHEN p.contype = \'p\' THEN \'PRIMARY KEY\'
+          WHEN p.contype = \'u\' THEN \'UNIQ\'
+          ELSE \'\' END
+        ||\'(\'||array_to_string(array_agg(f.attname),\', \')||\')\' AS sql
+    FROM pg_attribute f
+        JOIN pg_class c ON c.oid = f.attrelid
+        LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
+    WHERE c.relkind = \'r\'::char
+        AND f.attnum > 0
+        AND p.contype IN (\'u\',\'p\')
+    GROUP BY c.oid,p.contype,f.attrelid,c.relname
+    ORDER BY c.oid,f.attrelid
+  )
+ORDER BY prio DESC) sql
+WHERE sql.table=\'<NAME>\'
+GROUP BY sql.id,sql.table
+)
+WHEN \'v\' THEN trim(regexp_replace(pg_catalog.pg_get_viewdef(c.oid::pg_catalog.oid, true),\'\\s\\s+\',\' \',\'g\'))
+ELSE \'NOT\' END as sql
+FROM pg_catalog.pg_class c WHERE c.relname = \'<NAME>\' AND pg_catalog.pg_table_is_visible(c.oid)
+  ',
+),
+
+);
+?>
diff --git a/lib/php/db/types/sqlite.php b/lib/php/db/types/sqlite.php
new file mode 100644 (file)
index 0000000..bf71f92
--- /dev/null
@@ -0,0 +1,45 @@
+<?php
+$DB_TYPES['sqlite'] = array (
+'use_path' => true,
+'table.sql' => 'SELECT sql FROM sqlite_master WHERE name=\'<NAME>\'',
+
+'sqliteCreateFunction' => array (
+  'ip2int' => function ($value) { return ip2long($value); },
+  'concat' => function ($v1,$v2) { return $v1.$v2; },
+  'regexp' => function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS') {
+      if (isset($pattern, $data) === true) {
+        return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
+      }
+      return null;
+    }
+  ,
+  'to_char' => array(function ($value,$format) {
+      $replace = array(
+          'YYYY' => '%Y',
+          'MM' => '%m',
+          'WW' => '%W',
+          'DD' => '%d',
+      );
+      $format = str_replace(array_keys($replace),array_values($replace),$format);
+      return strftime($format,strtotime($value));
+    }
+  ,2),
+),
+
+'localFile' => array ('/Users/nico/.sqlite','^(?:user(?:name)?=(?P<user>\\S+)|password=(?P<password>\\S+))'),
+
+'tables' => 'SELECT name,type FROM sqlite_master WHERE type IN(\'table\',\'view\') AND name NOT LIKE \'sqlite_%\' ORDER BY name',
+
+'table.fields' => array (
+  'sql' => 'PRAGMA table_info(\'<NAME>\')',
+  'fct' => create_function('&$r',join('',array(
+    #'debug("zaza");',
+    '$r["key"] = $r["pk"] == "0" ? 0 : 1;',
+    '$r["default"] = $r["dflt_value"];',
+    '$r["null"] = $r["notnull"] == "0" ? 1 : 0;',
+    '$r["autoincrement"] = preg_match("/[\(,]".$r["name"]." [^\),]+ AUTOINCREMENT/",$r["this"]->sql()) ? 1 : 0;',
+  ))),
+),
+
+);
+?>
index d102ec1232ae72d8cc773e2d1f6cd89e7f761cb3..0a4ff75f0fc4a2b56ee271ca92b208e8ac2bd412 100644 (file)
@@ -73,7 +73,7 @@ class nb {
    * Set a value for param, delete it if null
    */
   public static function bye($msg='',$backtrace_deep=0) {
-    return bye($msg,$backtrace_deep);
+    return bye($msg,$backtrace_deep+1);
   }
 
   /*
@@ -239,7 +239,7 @@ class nb {
    * Call a function several times
    * Usage: benchmark("f1"); benchmark("f2"); benchmark();
    */
-  public static function benchmark($function=null,$limit=1000000) {
+  public static function benchmark($function=null,$limit=100000) {
     global $_benchmark;
 
     if ($_benchmark === null) {
@@ -454,187 +454,7 @@ class nb {
 
   public static function no_accent($str){
     return strtr($str,array(
-'À' => 'A',
-'Á' => 'A',
-'Â' => 'A',
-'Ã' => 'A',
-'Ä' => 'A',
-'Å' => 'A',
-'à' => 'a',
-'á' => 'a',
-'â' => 'a',
-'ã' => 'a',
-'ä' => 'a',
-'å' => 'a',
-'Ā' => 'A',
-'ā' => 'a',
-'Ă' => 'A',
-'ă' => 'a',
-'Ą' => 'A',
-'ą' => 'a',
-'Ç' => 'C',
-'ç' => 'c',
-'Ć' => 'C',
-'ć' => 'c',
-'Ĉ' => 'C',
-'ĉ' => 'c',
-'Ċ' => 'C',
-'ċ' => 'c',
-'Č' => 'C',
-'č' => 'c',
-'Ð' => 'D',
-'ð' => 'd',
-'Ď' => 'D',
-'ď' => 'd',
-'Đ' => 'D',
-'đ' => 'd',
-'È' => 'E',
-'É' => 'E',
-'Ê' => 'E',
-'Ë' => 'E',
-'è' => 'e',
-'é' => 'e',
-'ê' => 'e',
-'ë' => 'e',
-'Ē' => 'E',
-'ē' => 'e',
-'Ĕ' => 'E',
-'ĕ' => 'e',
-'Ė' => 'E',
-'ė' => 'e',
-'Ę' => 'E',
-'ę' => 'e',
-'Ě' => 'E',
-'ě' => 'e',
-'Ĝ' => 'G',
-'ĝ' => 'g',
-'Ğ' => 'G',
-'ğ' => 'g',
-'Ġ' => 'G',
-'ġ' => 'g',
-'Ģ' => 'G',
-'ģ' => 'g',
-'Ĥ' => 'H',
-'ĥ' => 'h',
-'Ħ' => 'H',
-'ħ' => 'h',
-'Ì' => 'I',
-'Í' => 'I',
-'Î' => 'I',
-'Ï' => 'I',
-'ì' => 'i',
-'í' => 'i',
-'î' => 'i',
-'ï' => 'i',
-'Ĩ' => 'I',
-'ĩ' => 'i',
-'Ī' => 'I',
-'ī' => 'i',
-'Ĭ' => 'I',
-'ĭ' => 'i',
-'Į' => 'I',
-'į' => 'i',
-'İ' => 'I',
-'ı' => 'i',
-'Ĵ' => 'J',
-'ĵ' => 'j',
-'Ķ' => 'K',
-'ķ' => 'k',
-'ĸ' => 'k',
-'Ĺ' => 'L',
-'ĺ' => 'l',
-'Ļ' => 'L',
-'ļ' => 'l',
-'Ľ' => 'L',
-'ľ' => 'l',
-'Ŀ' => 'L',
-'ŀ' => 'l',
-'Ł' => 'L',
-'ł' => 'l',
-'Ñ' => 'N',
-'ñ' => 'n',
-'Ń' => 'N',
-'ń' => 'n',
-'Ņ' => 'N',
-'ņ' => 'n',
-'Ň' => 'N',
-'ň' => 'n',
-'ʼn' => 'n',
-'Ŋ' => 'N',
-'ŋ' => 'n',
-'Ò' => 'O',
-'Ó' => 'O',
-'Ô' => 'O',
-'Õ' => 'O',
-'Ö' => 'O',
-'Ø' => 'O',
-'ò' => 'o',
-'ó' => 'o',
-'ô' => 'o',
-'õ' => 'o',
-'ö' => 'o',
-'ø' => 'o',
-'Ō' => 'O',
-'ō' => 'o',
-'Ŏ' => 'O',
-'ŏ' => 'o',
-'Ő' => 'O',
-'ő' => 'o',
-'Ŕ' => 'R',
-'ŕ' => 'r',
-'Ŗ' => 'R',
-'ŗ' => 'r',
-'Ř' => 'R',
-'ř' => 'r',
-'Ś' => 'S',
-'ś' => 's',
-'Ŝ' => 'S',
-'ŝ' => 's',
-'Ş' => 'S',
-'ş' => 's',
-'Š' => 'S',
-'š' => 's',
-'ſ' => 's',
-'Ţ' => 'T',
-'ţ' => 't',
-'Ť' => 'T',
-'ť' => 't',
-'Ŧ' => 'T',
-'ŧ' => 't',
-'Ù' => 'U',
-'Ú' => 'U',
-'Û' => 'U',
-'Ü' => 'U',
-'ù' => 'u',
-'ú' => 'u',
-'û' => 'u',
-'ü' => 'u',
-'Ũ' => 'U',
-'ũ' => 'u',
-'Ū' => 'U',
-'ū' => 'u',
-'Ŭ' => 'U',
-'ŭ' => 'u',
-'Ů' => 'U',
-'ů' => 'u',
-'Ű' => 'U',
-'ű' => 'u',
-'Ų' => 'U',
-'ų' => 'u',
-'Ŵ' => 'W',
-'ŵ' => 'w',
-'Ý' => 'Y',
-'ý' => 'y',
-'ÿ' => 'y',
-'Ŷ' => 'Y',
-'ŷ' => 'y',
-'Ÿ' => 'Y',
-'Ź' => 'Z',
-'ź' => 'z',
-'Ż' => 'Z',
-'ż' => 'z',
-'Ž' => 'Z',
-'ž' => 'z'
+      'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'Ā' => 'A', 'ā' => 'a', 'Ă' => 'A', 'ă' => 'a', 'Ą' => 'A', 'ą' => 'a', 'Ç' => 'C', 'ç' => 'c', 'Ć' => 'C', 'ć' => 'c', 'Ĉ' => 'C', 'ĉ' => 'c', 'Ċ' => 'C', 'ċ' => 'c', 'Č' => 'C', 'č' => 'c', 'Ð' => 'D', 'ð' => 'd', 'Ď' => 'D', 'ď' => 'd', 'Đ' => 'D', 'đ' => 'd', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'Ē' => 'E', 'ē' => 'e', 'Ĕ' => 'E', 'ĕ' => 'e', 'Ė' => 'E', 'ė' => 'e', 'Ę' => 'E', 'ę' => 'e', 'Ě' => 'E', 'ě' => 'e', 'Ĝ' => 'G', 'ĝ' => 'g', 'Ğ' => 'G', 'ğ' => 'g', 'Ġ' => 'G', 'ġ' => 'g', 'Ģ' => 'G', 'ģ' => 'g', 'Ĥ' => 'H', 'ĥ' => 'h', 'Ħ' => 'H', 'ħ' => 'h', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'Ĩ' => 'I', 'ĩ' => 'i', 'Ī' => 'I', 'ī' => 'i', 'Ĭ' => 'I', 'ĭ' => 'i', 'Į' => 'I', 'į' => 'i', 'İ' => 'I', 'ı' => 'i', 'Ĵ' => 'J', 'ĵ' => 'j', 'Ķ' => 'K', 'ķ' => 'k', 'ĸ' => 'k', 'Ĺ' => 'L', 'ĺ' => 'l', 'Ļ' => 'L', 'ļ' => 'l', 'Ľ' => 'L', 'ľ' => 'l', 'Ŀ' => 'L', 'ŀ' => 'l', 'Ł' => 'L', 'ł' => 'l', 'Ñ' => 'N', 'ñ' => 'n', 'Ń' => 'N', 'ń' => 'n', 'Ņ' => 'N', 'ņ' => 'n', 'Ň' => 'N', 'ň' => 'n', 'ʼn' => 'n', 'Ŋ' => 'N', 'ŋ' => 'n', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'Ō' => 'O', 'ō' => 'o', 'Ŏ' => 'O', 'ŏ' => 'o', 'Ő' => 'O', 'ő' => 'o', 'Ŕ' => 'R', 'ŕ' => 'r', 'Ŗ' => 'R', 'ŗ' => 'r', 'Ř' => 'R', 'ř' => 'r', 'Ś' => 'S', 'ś' => 's', 'Ŝ' => 'S', 'ŝ' => 's', 'Ş' => 'S', 'ş' => 's', 'Š' => 'S', 'š' => 's', 'ſ' => 's', 'Ţ' => 'T', 'ţ' => 't', 'Ť' => 'T', 'ť' => 't', 'Ŧ' => 'T', 'ŧ' => 't', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'Ũ' => 'U', 'ũ' => 'u', 'Ū' => 'U', 'ū' => 'u', 'Ŭ' => 'U', 'ŭ' => 'u', 'Ů' => 'U', 'ů' => 'u', 'Ű' => 'U', 'ű' => 'u', 'Ų' => 'U', 'ų' => 'u', 'Ŵ' => 'W', 'ŵ' => 'w', 'Ý' => 'Y', 'ý' => 'y', 'ÿ' => 'y', 'Ŷ' => 'Y', 'ŷ' => 'y', 'Ÿ' => 'Y', 'Ź' => 'Z', 'ź' => 'z', 'Ż' => 'Z', 'ż' => 'z', 'Ž' => 'Z', 'ž' => 'z'
     ));
   }
 } # < Class
index 33254800841c9a7d0690bc4ee1f7705678302f6e..91d7d427c64645275a620b5fd831126d9a70d5dd 100644 (file)
@@ -106,6 +106,7 @@ Class Out extends Nb {
   }
 
   public static function head(&$o,$head,$data=array()) {
+    if (is_scalar($head) and !is_bool($head)) $head = array($head);
 
     # For sprintf
     unset($o['head_max_len']);
@@ -201,8 +202,6 @@ Class Out extends Nb {
     $count = 0;
 
     # Function head
-    #elseif (is_scalar($head)) $head = array($head);
-    if (is_scalar($head) and !is_bool($head)) $head = array($head);
     self::head($conf,$head,$data);
 
     foreach ($data as $row) {
@@ -305,7 +304,6 @@ function out_csv(&$row,$o) {
   $values = array();
 
   foreach (array_values($row) as $k=>$v) {
-    #if (!is_scalar($v)) $v = join('',$v);
     $values[] = preg_replace('/zAZA/','',out::scalar($v));
     #$values[] = preg_replace('/\r?\n/','',out::scalar($v));
   }