/libs/dibi/dibi.min.php
PHP | 1788 lines | 1765 code | 4 blank | 19 comment | 3 complexity | fdbfd30d5494967a62e2557b54c3fd73 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php //netteloader=DibiVariable,IDataSource,IDibiProfiler,IDibiDriver,IDibiResultDriver,IDibiReflector,DibiObject,DibiLazyStorageBase,DibiLazyStorage,DibiException,DibiDriverException,DibiConnection,DibiResult,DibiResultIterator,DibiRow,DibiTranslator,DibiDataSource,DibiFluent,DibiDatabaseInfo,DibiTableInfo,DibiResultInfo,DibiColumnInfo,DibiForeignKeyInfo,DibiIndexInfo,DibiProfiler,dibi,DibiMySqlReflector,DibiMySqlDriver,DibiMySqliDriver,DibiOdbcDriver,DibiPdoDriver,DibiPostgreDriver,DibiSqliteReflector,DibiSqliteDriver,DibiSqlite3Driver
- /**
- * dibi - tiny'n'smart database abstraction layer
- * ----------------------------------------------
- *
- * Copyright (c) 2005, 2010 David Grudl (http://davidgrudl.com)
- *
- * This source file is subject to the "dibi license" that is bundled
- * with this package in the file license.txt, and/or GPL license.
- *
- * For more information please see http://dibiphp.com
- *
- * @copyright Copyright (c) 2005, 2010 David Grudl
- * @license http://dibiphp.com/license dibi license
- * @link http://dibiphp.com
- * @package dibi
- */
- if(version_compare(PHP_VERSION,'5.2.0','<')){throw
- new
- Exception('dibi needs PHP 5.2.0 or newer.');}@set_magic_quotes_runtime(FALSE);if(!class_exists('NotImplementedException',FALSE)){class
- NotImplementedException
- extends
- LogicException{}}if(!class_exists('NotSupportedException',FALSE)){class
- NotSupportedException
- extends
- LogicException{}}if(!class_exists('MemberAccessException',FALSE)){class
- MemberAccessException
- extends
- LogicException{}}if(!class_exists('InvalidStateException',FALSE)){class
- InvalidStateException
- extends
- RuntimeException{}}if(!class_exists('IOException',FALSE)){class
- IOException
- extends
- RuntimeException{}}if(!class_exists('FileNotFoundException',FALSE)){class
- FileNotFoundException
- extends
- IOException{}}if(!class_exists('PcreException',FALSE)){class
- PcreException
- extends
- Exception{public
- function
- __construct(){static$messages=array(PREG_INTERNAL_ERROR=>'Internal error.',PREG_BACKTRACK_LIMIT_ERROR=>'Backtrack limit was exhausted.',PREG_RECURSION_LIMIT_ERROR=>'Recursion limit was exhausted.',PREG_BAD_UTF8_ERROR=>'Malformed UTF-8 data.',5=>'Offset didn\'t correspond to the begin of a valid UTF-8 code point.');$code=preg_last_error();parent::__construct(isset($messages[$code])?$messages[$code]:'Unknown error.',$code);}}}if(!interface_exists('IDebugPanel',FALSE)){interface
- IDebugPanel{function
- getTab();function
- getPanel();function
- getId();}}if(!class_exists('DateTime53',FALSE)){class
- DateTime53
- extends
- DateTime{public
- function
- __sleep(){$this->fix=array($this->format('Y-m-d H:i:s'),$this->getTimezone()->getName());return
- array('fix');}public
- function
- __wakeup(){$this->__construct($this->fix[0],new
- DateTimeZone($this->fix[1]));unset($this->fix);}public
- function
- getTimestamp(){return(int)$this->format('U');}public
- function
- setTimestamp($timestamp){return$this->__construct(date('Y-m-d H:i:s',$timestamp),new
- DateTimeZone($this->getTimezone()->getName()));}}}class
- DibiVariable
- extends
- DateTime53{function
- __construct($val){parent::__construct($val);}}interface
- IDataSource
- extends
- Countable,IteratorAggregate{}interface
- IDibiProfiler{const
- CONNECT=1;const
- SELECT=4;const
- INSERT=8;const
- DELETE=16;const
- UPDATE=32;const
- QUERY=60;const
- BEGIN=64;const
- COMMIT=128;const
- ROLLBACK=256;const
- TRANSACTION=448;const
- EXCEPTION=512;const
- ALL=1023;function
- before(DibiConnection$connection,$event,$sql=NULL);function
- after($ticket,$result=NULL);function
- exception(DibiDriverException$exception);}interface
- IDibiDriver{function
- connect(array&$config);function
- disconnect();function
- query($sql);function
- getAffectedRows();function
- getInsertId($sequence);function
- begin($savepoint=NULL);function
- commit($savepoint=NULL);function
- rollback($savepoint=NULL);function
- getResource();function
- getReflector();function
- escape($value,$type);function
- applyLimit(&$sql,$limit,$offset);}interface
- IDibiResultDriver{function
- getRowCount();function
- seek($row);function
- fetch($type);function
- free();function
- getResultColumns();function
- getResultResource();function
- unescape($value,$type);}interface
- IDibiReflector{function
- getTables();function
- getColumns($table);function
- getIndexes($table);function
- getForeignKeys($table);}abstract
- class
- DibiObject{private
- static$extMethods;final
- public
- function
- getClass(){return
- get_class($this);}final
- public
- function
- getReflection(){return
- new
- ReflectionObject($this);}public
- function
- __call($name,$args){$class=get_class($this);if($name===''){throw
- new
- MemberAccessException("Call to class '$class' method without name.");}if(preg_match('#^on[A-Z]#',$name)){$rp=new
- ReflectionProperty($class,$name);if($rp->isPublic()&&!$rp->isStatic()){$list=$this->$name;if(is_array($list)||$list
- instanceof
- Traversable){foreach($list
- as$handler){if(is_object($handler)){call_user_func_array(array($handler,'__invoke'),$args);}else{call_user_func_array($handler,$args);}}}return
- NULL;}}if($cb=self::extensionMethod("$class::$name")){array_unshift($args,$this);return
- call_user_func_array($cb,$args);}throw
- new
- MemberAccessException("Call to undefined method $class::$name().");}public
- static
- function
- __callStatic($name,$args){$class=get_called_class();throw
- new
- MemberAccessException("Call to undefined static method $class::$name().");}public
- static
- function
- extensionMethod($name,$callback=NULL){if(self::$extMethods===NULL||$name===NULL){$list=get_defined_functions();foreach($list['user']as$fce){$pair=explode('_prototype_',$fce);if(count($pair)===2){self::$extMethods[$pair[1]][$pair[0]]=$fce;self::$extMethods[$pair[1]]['']=NULL;}}if($name===NULL)return
- NULL;}$name=strtolower($name);$a=strrpos($name,':');if($a===FALSE){$class=strtolower(get_called_class());$l=&self::$extMethods[$name];}else{$class=substr($name,0,$a-1);$l=&self::$extMethods[substr($name,$a+1)];}if($callback!==NULL){$l[$class]=$callback;$l['']=NULL;return
- NULL;}if(empty($l)){return
- FALSE;}elseif(isset($l[''][$class])){return$l[''][$class];}$cl=$class;do{$cl=strtolower($cl);if(isset($l[$cl])){return$l[''][$class]=$l[$cl];}}while(($cl=get_parent_class($cl))!==FALSE);foreach(class_implements($class)as$cl){$cl=strtolower($cl);if(isset($l[$cl])){return$l[''][$class]=$l[$cl];}}return$l[''][$class]=FALSE;}public
- function&__get($name){$class=get_class($this);if($name===''){throw
- new
- MemberAccessException("Cannot read a class '$class' property without name.");}$name[0]=$name[0]&"\xDF";$m='get'.$name;if(self::hasAccessor($class,$m)){$val=$this->$m();return$val;}$m='is'.$name;if(self::hasAccessor($class,$m)){$val=$this->$m();return$val;}$name=func_get_arg(0);throw
- new
- MemberAccessException("Cannot read an undeclared property $class::\$$name.");}public
- function
- __set($name,$value){$class=get_class($this);if($name===''){throw
- new
- MemberAccessException("Cannot assign to a class '$class' property without name.");}$name[0]=$name[0]&"\xDF";if(self::hasAccessor($class,'get'.$name)||self::hasAccessor($class,'is'.$name)){$m='set'.$name;if(self::hasAccessor($class,$m)){$this->$m($value);return;}else{$name=func_get_arg(0);throw
- new
- MemberAccessException("Cannot assign to a read-only property $class::\$$name.");}}$name=func_get_arg(0);throw
- new
- MemberAccessException("Cannot assign to an undeclared property $class::\$$name.");}public
- function
- __isset($name){$name[0]=$name[0]&"\xDF";return$name!==''&&self::hasAccessor(get_class($this),'get'.$name);}public
- function
- __unset($name){$class=get_class($this);throw
- new
- MemberAccessException("Cannot unset the property $class::\$$name.");}private
- static
- function
- hasAccessor($c,$m){static$cache;if(!isset($cache[$c])){$cache[$c]=array_flip(get_class_methods($c));}return
- isset($cache[$c][$m]);}}abstract
- class
- DibiLazyStorageBase{private$callback;public
- function
- __construct($callback){$this->setCallback($callback);}public
- function
- setCallback($callback){if(!is_callable($callback)){$able=is_callable($callback,TRUE,$textual);throw
- new
- InvalidArgumentException("Handler '$textual' is not ".($able?'callable.':'valid PHP callback.'));}$this->callback=$callback;}public
- function
- getCallback(){return$this->callback;}}final
- class
- DibiLazyStorage
- extends
- DibiLazyStorageBase{public
- function
- __get($nm){if(is_array($nm)){$nm=$nm[1];}if($nm==''){throw
- new
- InvalidStateException('Missing identifier name.');}return$this->$nm=call_user_func($this->getCallback(),$nm);}}class
- DibiException
- extends
- Exception
- implements
- IDebugPanel{private$sql;public
- function
- __construct($message=NULL,$code=0,$sql=NULL){parent::__construct($message,(int)$code);$this->sql=$sql;}final
- public
- function
- getSql(){return$this->sql;}public
- function
- __toString(){return
- parent::__toString().($this->sql?"\nSQL: ".$this->sql:'');}public
- function
- getTab(){return'SQL';}public
- function
- getPanel(){return$this->sql?dibi::dump($this->sql,TRUE):NULL;}public
- function
- getId(){return
- __CLASS__;}}class
- DibiDriverException
- extends
- DibiException{private
- static$errorMsg;public
- static
- function
- tryError(){set_error_handler(array(__CLASS__,'_errorHandler'),E_ALL);self::$errorMsg=NULL;}public
- static
- function
- catchError(&$message){restore_error_handler();$message=self::$errorMsg;self::$errorMsg=NULL;return$message!==NULL;}public
- static
- function
- _errorHandler($code,$message){restore_error_handler();if(ini_get('html_errors')){$message=strip_tags($message);$message=html_entity_decode($message);}self::$errorMsg=$message;}}class
- DibiConnection
- extends
- DibiObject{private$config;private$driver;private$translator;private$profiler;private$connected=FALSE;public
- function
- __construct($config,$name=NULL){if(is_string($config)){parse_str($config,$config);}elseif($config
- instanceof
- Traversable){$tmp=array();foreach($config
- as$key=>$val){$tmp[$key]=$val
- instanceof
- Traversable?iterator_to_array($val):$val;}$config=$tmp;}elseif(!is_array($config)){throw
- new
- InvalidArgumentException('Configuration must be array, string or object.');}self::alias($config,'username','user');self::alias($config,'password','pass');self::alias($config,'host','hostname');self::alias($config,'result|detectTypes','resultDetectTypes');self::alias($config,'result|formatDateTime','resultDateTime');if(!isset($config['driver'])){$config['driver']=dibi::$defaultDriver;}$driver=preg_replace('#[^a-z0-9_]#','_',strtolower($config['driver']));$class="Dibi".$driver."Driver";if(!class_exists($class,FALSE)){ include_once dirname(__FILE__)."/../drivers/$driver.php";if(!class_exists($class,FALSE)){throw
- new
- DibiException("Unable to create instance of dibi driver '$class'.");}}$config['name']=$name;$this->config=$config;$this->driver=new$class;$this->translator=new
- DibiTranslator($this->driver);$profilerCfg=&$config['profiler'];if(is_scalar($profilerCfg)){$profilerCfg=array('run'=>(bool)$profilerCfg,'class'=>strlen($profilerCfg)>1?$profilerCfg:NULL);}if(!empty($profilerCfg['run'])){$class=isset($profilerCfg['class'])?$profilerCfg['class']:'DibiProfiler';if(!class_exists($class)){throw
- new
- DibiException("Unable to create instance of dibi profiler '$class'.");}$this->setProfiler(new$class($profilerCfg));}if(!empty($config['substitutes'])){foreach($config['substitutes']as$key=>$value){dibi::addSubst($key,$value);}}if(empty($config['lazy'])){$this->connect();}}public
- function
- __destruct(){$this->connected&&$this->disconnect();}final
- public
- function
- connect(){if($this->profiler!==NULL){$ticket=$this->profiler->before($this,IDibiProfiler::CONNECT);}$this->driver->connect($this->config);$this->connected=TRUE;if(isset($ticket)){$this->profiler->after($ticket);}}final
- public
- function
- disconnect(){$this->driver->disconnect();$this->connected=FALSE;}final
- public
- function
- isConnected(){return$this->connected;}final
- public
- function
- getConfig($key=NULL,$default=NULL){if($key===NULL){return$this->config;}elseif(isset($this->config[$key])){return$this->config[$key];}else{return$default;}}public
- static
- function
- alias(&$config,$key,$alias){$foo=&$config;foreach(explode('|',$key)as$key)$foo=&$foo[$key];if(!isset($foo)&&isset($config[$alias])){$foo=$config[$alias];unset($config[$alias]);}}final
- public
- function
- getDriver(){$this->connected||$this->connect();return$this->driver;}final
- public
- function
- query($args){$this->connected||$this->connect();$args=func_get_args();return$this->nativeQuery($this->translator->translate($args));}final
- public
- function
- translate($args){$this->connected||$this->connect();$args=func_get_args();return$this->translator->translate($args);}function
- sql($args){trigger_error(__METHOD__.'() is deprecated; use translate() instead.',E_USER_NOTICE);$this->connected||$this->connect();$args=func_get_args();return$this->translator->translate($args);}final
- public
- function
- test($args){$this->connected||$this->connect();$args=func_get_args();try{dibi::dump($this->translator->translate($args));return
- TRUE;}catch(DibiException$e){dibi::dump($e->getSql());return
- FALSE;}}final
- public
- function
- dataSource($args){$this->connected||$this->connect();$args=func_get_args();return
- new
- DibiDataSource($this->translator->translate($args),$this);}final
- public
- function
- nativeQuery($sql){$this->connected||$this->connect();if($this->profiler!==NULL){$event=IDibiProfiler::QUERY;if(preg_match('#\s*(SELECT|UPDATE|INSERT|DELETE)#i',$sql,$matches)){static$events=array('SELECT'=>IDibiProfiler::SELECT,'UPDATE'=>IDibiProfiler::UPDATE,'INSERT'=>IDibiProfiler::INSERT,'DELETE'=>IDibiProfiler::DELETE);$event=$events[strtoupper($matches[1])];}$ticket=$this->profiler->before($this,$event,$sql);}dibi::$sql=$sql;if($res=$this->driver->query($sql)){$res=new
- DibiResult($res,$this->config['result']);}else{$res=$this->driver->getAffectedRows();}if(isset($ticket)){$this->profiler->after($ticket,$res);}return$res;}public
- function
- getAffectedRows(){$this->connected||$this->connect();$rows=$this->driver->getAffectedRows();if(!is_int($rows)||$rows<0)throw
- new
- DibiException('Cannot retrieve number of affected rows.');return$rows;}public
- function
- affectedRows(){return$this->getAffectedRows();}public
- function
- getInsertId($sequence=NULL){$this->connected||$this->connect();$id=$this->driver->getInsertId($sequence);if($id<1)throw
- new
- DibiException('Cannot retrieve last generated ID.');return(int)$id;}public
- function
- insertId($sequence=NULL){return$this->getInsertId($sequence);}public
- function
- begin($savepoint=NULL){$this->connected||$this->connect();if($this->profiler!==NULL){$ticket=$this->profiler->before($this,IDibiProfiler::BEGIN,$savepoint);}$this->driver->begin($savepoint);if(isset($ticket)){$this->profiler->after($ticket);}}public
- function
- commit($savepoint=NULL){$this->connected||$this->connect();if($this->profiler!==NULL){$ticket=$this->profiler->before($this,IDibiProfiler::COMMIT,$savepoint);}$this->driver->commit($savepoint);if(isset($ticket)){$this->profiler->after($ticket);}}public
- function
- rollback($savepoint=NULL){$this->connected||$this->connect();if($this->profiler!==NULL){$ticket=$this->profiler->before($this,IDibiProfiler::ROLLBACK,$savepoint);}$this->driver->rollback($savepoint);if(isset($ticket)){$this->profiler->after($ticket);}}public
- function
- command(){return
- new
- DibiFluent($this);}public
- function
- select($args){$args=func_get_args();return$this->command()->__call('select',$args);}public
- function
- update($table,$args){if(!(is_array($args)||$args
- instanceof
- Traversable)){throw
- new
- InvalidArgumentException('Arguments must be array or Traversable.');}return$this->command()->update('%n',$table)->set($args);}public
- function
- insert($table,$args){if($args
- instanceof
- Traversable){$args=iterator_to_array($args);}elseif(!is_array($args)){throw
- new
- InvalidArgumentException('Arguments must be array or Traversable.');}return$this->command()->insert()->into('%n',$table,'(%n)',array_keys($args))->values('%l',$args);}public
- function
- delete($table){return$this->command()->delete()->from('%n',$table);}public
- function
- setProfiler(IDibiProfiler$profiler=NULL){$this->profiler=$profiler;return$this;}public
- function
- getProfiler(){return$this->profiler;}public
- function
- fetch($args){$args=func_get_args();return$this->query($args)->fetch();}public
- function
- fetchAll($args){$args=func_get_args();return$this->query($args)->fetchAll();}public
- function
- fetchSingle($args){$args=func_get_args();return$this->query($args)->fetchSingle();}public
- function
- fetchPairs($args){$args=func_get_args();return$this->query($args)->fetchPairs();}public
- function
- loadFile($file){$this->connected||$this->connect();@set_time_limit(0);$handle=@fopen($file,'r');if(!$handle){throw
- new
- FileNotFoundException("Cannot open file '$file'.");}$count=0;$sql='';while(!feof($handle)){$s=fgets($handle);$sql.=$s;if(substr(rtrim($s),-1)===';'){$this->driver->query($sql);$sql='';$count++;}}fclose($handle);return$count;}public
- function
- getDatabaseInfo(){$this->connected||$this->connect();return
- new
- DibiDatabaseInfo($this->driver->getReflector(),isset($this->config['database'])?$this->config['database']:NULL);}public
- function
- __wakeup(){throw
- new
- NotSupportedException('You cannot serialize or unserialize '.$this->getClass().' instances.');}public
- function
- __sleep(){throw
- new
- NotSupportedException('You cannot serialize or unserialize '.$this->getClass().' instances.');}}class
- DibiResult
- extends
- DibiObject
- implements
- IDataSource{private$driver;private$types;private$meta;private$fetched=FALSE;private$rowClass='DibiRow';private$dateFormat='';public
- function
- __construct($driver,$config){$this->driver=$driver;if(!empty($config['detectTypes'])){$this->detectTypes();}if(!empty($config['formatDateTime'])){$this->dateFormat=is_string($config['formatDateTime'])?$config['formatDateTime']:'';}}final
- public
- function
- getResource(){return$this->getDriver()->getResultResource();}final
- public
- function
- free(){if($this->driver!==NULL){$this->driver->free();$this->driver=$this->meta=NULL;}}private
- function
- getDriver(){if($this->driver===NULL){throw
- new
- InvalidStateException('Result-set was released from memory.');}return$this->driver;}final
- public
- function
- seek($row){return($row!==0||$this->fetched)?(bool)$this->getDriver()->seek($row):TRUE;}final
- public
- function
- count(){return$this->getDriver()->getRowCount();}final
- public
- function
- getRowCount(){return$this->getDriver()->getRowCount();}final
- public
- function
- rowCount(){return$this->getDriver()->getRowCount();}final
- public
- function
- getIterator(){if(func_num_args()){trigger_error(__METHOD__.' arguments $offset & $limit have been dropped; use SQL clauses instead.',E_USER_WARNING);}return
- new
- DibiResultIterator($this);}public
- function
- setRowClass($class){$this->rowClass=$class;return$this;}public
- function
- getRowClass(){return$this->rowClass;}final
- public
- function
- fetch(){$row=$this->getDriver()->fetch(TRUE);if(!is_array($row))return
- FALSE;$this->fetched=TRUE;if($this->types!==NULL){foreach($this->types
- as$col=>$type){if(isset($row[$col])){$row[$col]=$this->convert($row[$col],$type);}}}return
- new$this->rowClass($row);}final
- public
- function
- fetchSingle(){$row=$this->getDriver()->fetch(TRUE);if(!is_array($row))return
- FALSE;$this->fetched=TRUE;$value=reset($row);$key=key($row);if(isset($this->types[$key])){return$this->convert($value,$this->types[$key]);}return$value;}final
- public
- function
- fetchAll($offset=NULL,$limit=NULL){$limit=$limit===NULL?-1:(int)$limit;$this->seek((int)$offset);$row=$this->fetch();if(!$row)return
- array();$data=array();do{if($limit===0)break;$limit--;$data[]=$row;}while($row=$this->fetch());return$data;}final
- public
- function
- fetchAssoc($assoc){if(strpos($assoc,',')!==FALSE){return$this->oldFetchAssoc($assoc);}$this->seek(0);$row=$this->fetch();if(!$row)return
- array();$data=NULL;$assoc=preg_split('#(\[\]|->|=|\|)#',$assoc,NULL,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);foreach($assoc
- as$as){if($as!=='[]'&&$as!=='='&&$as!=='->'&&$as!=='|'&&!property_exists($row,$as)){throw
- new
- InvalidArgumentException("Unknown column '$as' in associative descriptor.");}}if($as==='->'){array_pop($assoc);}if(empty($assoc)){$assoc[]='[]';}do{$x=&$data;foreach($assoc
- as$i=>$as){if($as==='[]'){$x=&$x[];}elseif($as==='='){$x=$row->{$assoc[$i+1]};continue
- 2;}elseif($as==='->'){if($x===NULL){$x=clone$row;$x=&$x->{$assoc[$i+1]};$x=NULL;}else{$x=&$x->{$assoc[$i+1]};}}elseif($as!=='|'){$x=&$x[$row->$as];}}if($x===NULL){$x=$row;}}while($row=$this->fetch());unset($x);return$data;}private
- function
- oldFetchAssoc($assoc){$this->seek(0);$row=$this->fetch();if(!$row)return
- array();$data=NULL;$assoc=explode(',',$assoc);$leaf='@';$last=count($assoc)-1;while($assoc[$last]==='='||$assoc[$last]==='@'){$leaf=$assoc[$last];unset($assoc[$last]);$last--;if($last<0){$assoc[]='#';break;}}do{$x=&$data;foreach($assoc
- as$i=>$as){if($as==='#'){$x=&$x[];}elseif($as==='='){if($x===NULL){$x=$row->toArray();$x=&$x[$assoc[$i+1]];$x=NULL;}else{$x=&$x[$assoc[$i+1]];}}elseif($as==='@'){if($x===NULL){$x=clone$row;$x=&$x->{$assoc[$i+1]};$x=NULL;}else{$x=&$x->{$assoc[$i+1]};}}else{$x=&$x[$row->$as];}}if($x===NULL){if($leaf==='='){$x=$row->toArray();}else{$x=$row;}}}while($row=$this->fetch());unset($x);return$data;}final
- public
- function
- fetchPairs($key=NULL,$value=NULL){$this->seek(0);$row=$this->fetch();if(!$row)return
- array();$data=array();if($value===NULL){if($key!==NULL){throw
- new
- InvalidArgumentException("Either none or both columns must be specified.");}$tmp=array_keys($row->toArray());$key=$tmp[0];if(count($row)<2){do{$data[]=$row[$key];}while($row=$this->fetch());return$data;}$value=$tmp[1];}else{if(!property_exists($row,$value)){throw
- new
- InvalidArgumentException("Unknown value column '$value'.");}if($key===NULL){do{$data[]=$row[$value];}while($row=$this->fetch());return$data;}if(!property_exists($row,$key)){throw
- new
- InvalidArgumentException("Unknown key column '$key'.");}}do{$data[$row[$key]]=$row[$value];}while($row=$this->fetch());return$data;}final
- public
- function
- setType($col,$type){$this->types[$col]=$type;return$this;}final
- public
- function
- detectTypes(){foreach($this->getInfo()->getColumns()as$col){$this->types[$col->getName()]=$col->getType();}}final
- public
- function
- setTypes(array$types){$this->types=$types;return$this;}final
- public
- function
- getType($col){return
- isset($this->types[$col])?$this->types[$col]:NULL;}protected
- function
- convert($value,$type){if($value===NULL||$value===FALSE){return
- NULL;}switch($type){case
- dibi::TEXT:return(string)$value;case
- dibi::BINARY:return$this->getDriver()->unescape($value,$type);case
- dibi::INTEGER:return(int)$value;case
- dibi::FLOAT:return(float)$value;case
- dibi::DATE:case
- dibi::DATETIME:if((int)$value===0){return
- NULL;}elseif($this->dateFormat===''){return
- new
- DateTime53(is_numeric($value)?date('Y-m-d H:i:s',$value):$value);}elseif($this->dateFormat==='U'){return
- is_numeric($value)?(int)$value:strtotime($value);}elseif(is_numeric($value)){return
- date($this->dateFormat,$value);}else{$value=new
- DateTime53($value);return$value->format($this->dateFormat);}case
- dibi::BOOL:return((bool)$value)&&$value!=='f'&&$value!=='F';default:return$value;}}public
- function
- getInfo(){if($this->meta===NULL){$this->meta=new
- DibiResultInfo($this->getDriver());}return$this->meta;}final
- public
- function
- getColumns(){return$this->getInfo()->getColumns();}public
- function
- getColumnNames($fullNames=FALSE){return$this->getInfo()->getColumnNames($fullNames);}final
- public
- function
- dump(){$i=0;$this->seek(0);while($row=$this->fetch()){if($i===0){echo"\n<table class=\"dump\">\n<thead>\n\t<tr>\n\t\t<th>#row</th>\n";foreach($row
- as$col=>$foo){echo"\t\t<th>".htmlSpecialChars($col)."</th>\n";}echo"\t</tr>\n</thead>\n<tbody>\n";}echo"\t<tr>\n\t\t<th>",$i,"</th>\n";foreach($row
- as$col){echo"\t\t<td>",htmlSpecialChars($col),"</td>\n";}echo"\t</tr>\n";$i++;}if($i===0){echo'<p><em>empty result set</em></p>';}else{echo"</tbody>\n</table>\n";}}}class
- DibiResultIterator
- implements
- Iterator,Countable{private$result;private$row;private$pointer;public
- function
- __construct(DibiResult$result){$this->result=$result;}public
- function
- rewind(){$this->pointer=0;$this->result->seek(0);$this->row=$this->result->fetch();}public
- function
- key(){return$this->pointer;}public
- function
- current(){return$this->row;}public
- function
- next(){$this->row=$this->result->fetch();$this->pointer++;}public
- function
- valid(){return!empty($this->row);}public
- function
- count(){return$this->result->getRowCount();}}class
- DibiRow
- implements
- ArrayAccess,IteratorAggregate,Countable{public
- function
- __construct($arr){foreach($arr
- as$k=>$v)$this->$k=$v;}public
- function
- toArray(){return(array)$this;}public
- function
- asDateTime($key,$format=NULL){$time=$this[$key];if((int)$time===0){return
- NULL;}$dt=new
- DateTime53(is_numeric($time)?date('Y-m-d H:i:s',$time):$time);return$format===NULL?$dt:$dt->format($format);}public
- function
- asTimestamp($key){$time=$this[$key];return(int)$time===0?NULL:(is_numeric($time)?(int)$time:strtotime($time));}public
- function
- asBool($key){$value=$this[$key];if($value===NULL||$value===FALSE){return$value;}else{return((bool)$value)&&$value!=='f'&&$value!=='F';}}public
- function
- asDate($key,$format=NULL){if($format===NULL){return$this->asTimestamp($key);}else{return$this->asDateTime($key,$format===TRUE?NULL:$format);}}final
- public
- function
- count(){return
- count((array)$this);}final
- public
- function
- getIterator(){return
- new
- ArrayIterator($this);}final
- public
- function
- offsetSet($nm,$val){$this->$nm=$val;}final
- public
- function
- offsetGet($nm){return$this->$nm;}final
- public
- function
- offsetExists($nm){return
- isset($this->$nm);}final
- public
- function
- offsetUnset($nm){unset($this->$nm);}}final
- class
- DibiTranslator
- extends
- DibiObject{private$driver;private$cursor;private$args;private$hasError;private$comment;private$ifLevel;private$ifLevelStart;private$limit;private$offset;private$identifiers;public
- function
- __construct(IDibiDriver$driver){$this->driver=$driver;$this->identifiers=new
- DibiLazyStorage(array($this,'delimite'));}public
- function
- translate(array$args){$args=array_values($args);while(count($args)===1&&is_array($args[0])){$args=array_values($args[0]);}$this->args=$args;$this->limit=-1;$this->offset=0;$this->hasError=FALSE;$commandIns=NULL;$lastArr=NULL;$cursor=&$this->cursor;$cursor=0;$this->ifLevel=$this->ifLevelStart=0;$comment=&$this->comment;$comment=FALSE;$sql=array();while($cursor<count($this->args)){$arg=$this->args[$cursor];$cursor++;if(is_string($arg)){$toSkip=strcspn($arg,'`[\'":%');if(strlen($arg)===$toSkip){$sql[]=$arg;}else{$sql[]=substr($arg,0,$toSkip).preg_replace_callback('/(?=[`[\'":%?])(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|:(\S*?:)([a-zA-Z0-9._]?)|%([a-zA-Z]{1,4})(?![a-zA-Z])|(\?))/s',array($this,'cb'),substr($arg,$toSkip));if(preg_last_error())throw
- new
- PcreException;}continue;}if($comment){$sql[]='...';continue;}if($arg
- instanceof
- Traversable){$arg=iterator_to_array($arg);}if(is_array($arg)){if(is_string(key($arg))){if($commandIns===NULL){$commandIns=strtoupper(substr(ltrim($this->args[0]),0,6));$commandIns=$commandIns==='INSERT'||$commandIns==='REPLAC';$sql[]=$this->formatValue($arg,$commandIns?'v':'a');}else{if($lastArr===$cursor-1)$sql[]=',';$sql[]=$this->formatValue($arg,$commandIns?'l':'a');}$lastArr=$cursor;continue;}}$sql[]=$this->formatValue($arg,FALSE);}if($comment)$sql[]="*/";$sql=implode(' ',$sql);if($this->hasError){throw
- new
- DibiException('SQL translate error',0,$sql);}if($this->limit>-1||$this->offset>0){$this->driver->applyLimit($sql,$this->limit,$this->offset);}return$sql;}public
- function
- formatValue($value,$modifier){if($value
- instanceof
- Traversable){$value=iterator_to_array($value);}if(is_array($value)){$vx=$kx=array();switch($modifier){case'and':case'or':if(empty($value)){return'1=1';}foreach($value
- as$k=>$v){if(is_string($k)){$pair=explode('%',$k,2);$k=$this->identifiers->{$pair[0]}.' ';if(!isset($pair[1])){$v=$this->formatValue($v,FALSE);$vx[]=$k.($v==='NULL'?'IS ':'= ').$v;}elseif($pair[1]==='ex'){$vx[]=$k.$this->formatValue($v,'ex');}else{$v=$this->formatValue($v,$pair[1]);$vx[]=$k.($pair[1]==='l'||$pair[1]==='in'?'IN ':($v==='NULL'?'IS ':'= ')).$v;}}else{$vx[]=$this->formatValue($v,'ex');}}return'('.implode(') '.strtoupper($modifier).' (',$vx).')';case'n':foreach($value
- as$k=>$v){if(is_string($k)){$vx[]=$this->identifiers->$k.(empty($v)?'':' AS '.$v);}else{$pair=explode('%',$v,2);$vx[]=$this->identifiers->{$pair[0]};}}return
- implode(', ',$vx);case'a':foreach($value
- as$k=>$v){$pair=explode('%',$k,2);$vx[]=$this->identifiers->{$pair[0]}.'='.$this->formatValue($v,isset($pair[1])?$pair[1]:(is_array($v)?'ex':FALSE));}return
- implode(', ',$vx);case'in':case'l':foreach($value
- as$k=>$v){$pair=explode('%',$k,2);$vx[]=$this->formatValue($v,isset($pair[1])?$pair[1]:(is_array($v)?'ex':FALSE));}return'('.(($vx||$modifier==='l')?implode(', ',$vx):'NULL').')';case'v':foreach($value
- as$k=>$v){$pair=explode('%',$k,2);$kx[]=$this->identifiers->{$pair[0]};$vx[]=$this->formatValue($v,isset($pair[1])?$pair[1]:(is_array($v)?'ex':FALSE));}return'('.implode(', ',$kx).') VALUES ('.implode(', ',$vx).')';case'm':foreach($value
- as$k=>$v){if(is_array($v)){if(isset($proto)){if($proto!==array_keys($v)){$this->hasError=TRUE;return'**Multi-insert array "'.$k.'" is different.**';}}else{$proto=array_keys($v);}}else{$this->hasError=TRUE;return'**Unexpected type '.gettype($v).'**';}$pair=explode('%',$k,2);$kx[]=$this->identifiers->{$pair[0]};foreach($v
- as$k2=>$v2){$vx[$k2][]=$this->formatValue($v2,isset($pair[1])?$pair[1]:(is_array($v2)?'ex':FALSE));}}foreach($vx
- as$k=>$v){$vx[$k]='('.implode(', ',$v).')';}return'('.implode(', ',$kx).') VALUES '.implode(', ',$vx);case'by':foreach($value
- as$k=>$v){if(is_array($v)){$vx[]=$this->formatValue($v,'ex');}elseif(is_string($k)){$v=(is_string($v)&&strncasecmp($v,'d',1))||$v>0?'ASC':'DESC';$vx[]=$this->identifiers->$k.' '.$v;}else{$vx[]=$this->identifiers->$v;}}return
- implode(', ',$vx);case'ex':case'sql':$translator=new
- self($this->driver);return$translator->translate($value);default:foreach($value
- as$v){$vx[]=$this->formatValue($v,$modifier);}return
- implode(', ',$vx);}}if($modifier){if($value!==NULL&&!is_scalar($value)&&!($value
- instanceof
- DateTime)){$this->hasError=TRUE;return'**Unexpected type '.gettype($value).'**';}switch($modifier){case's':case'bin':case'b':return$value===NULL?'NULL':$this->driver->escape($value,$modifier);case'sN':case'sn':return$value==''?'NULL':$this->driver->escape($value,dibi::TEXT);case'iN':case'in':if($value=='')$value=NULL;case'i':case'u':if(is_string($value)&&preg_match('#[+-]?\d++(e\d+)?$#A',$value)){return$value;}else{return$value===NULL?'NULL':(string)(int)($value+0);}case'f':if(is_string($value)&&is_numeric($value)&&strpos($value,'x')===FALSE){return$value;}else{return$value===NULL?'NULL':rtrim(rtrim(number_format($value+0,5,'.',''),'0'),'.');}case'd':case't':if($value===NULL){return'NULL';}else{if(is_numeric($value)){$value=(int)$value;}elseif(is_string($value)){$value=new
- DateTime($value);}return$this->driver->escape($value,$modifier);}case'by':case'n':return$this->identifiers->$value;case'ex':case'sql':$value=(string)$value;$toSkip=strcspn($value,'`[\'":');if(strlen($value)!==$toSkip){$value=substr($value,0,$toSkip).preg_replace_callback('/(?=[`[\'":])(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|:(\S*?:)([a-zA-Z0-9._]?))/s',array($this,'cb'),substr($value,$toSkip));if(preg_last_error())throw
- new
- PcreException;}return$value;case'SQL':return(string)$value;case'and':case'or':case'a':case'l':case'v':$this->hasError=TRUE;return'**Unexpected type '.gettype($value).'**';default:$this->hasError=TRUE;return"**Unknown or invalid modifier %$modifier**";}}if(is_string($value)){return$this->driver->escape($value,dibi::TEXT);}elseif(is_int($value)){return(string)$value;}elseif(is_float($value)){return
- rtrim(rtrim(number_format($value,5,'.',''),'0'),'.');}elseif(is_bool($value)){return$this->driver->escape($value,dibi::BOOL);}elseif($value===NULL){return'NULL';}elseif($value
- instanceof
- DateTime){return$this->driver->escape($value,dibi::DATETIME);}else{$this->hasError=TRUE;return'**Unexpected '.gettype($value).'**';}}private
- function
- cb($matches){if(!empty($matches[11])){$cursor=&$this->cursor;if($cursor>=count($this->args)){$this->hasError=TRUE;return"**Extra placeholder**";}$cursor++;return$this->formatValue($this->args[$cursor-1],FALSE);}if(!empty($matches[10])){$mod=$matches[10];$cursor=&$this->cursor;if($cursor>=count($this->args)&&$mod!=='else'&&$mod!=='end'){$this->hasError=TRUE;return"**Extra modifier %$mod**";}if($mod==='if'){$this->ifLevel++;$cursor++;if(!$this->comment&&!$this->args[$cursor-1]){$this->ifLevelStart=$this->ifLevel;$this->comment=TRUE;return"/*";}return'';}elseif($mod==='else'){if($this->ifLevelStart===$this->ifLevel){$this->ifLevelStart=0;$this->comment=FALSE;return"*/";}elseif(!$this->comment){$this->ifLevelStart=$this->ifLevel;$this->comment=TRUE;return"/*";}}elseif($mod==='end'){$this->ifLevel--;if($this->ifLevelStart===$this->ifLevel+1){$this->ifLevelStart=0;$this->comment=FALSE;return"*/";}return'';}elseif($mod==='ex'){array_splice($this->args,$cursor,1,$this->args[$cursor]);return'';}elseif($mod==='lmt'){if($this->args[$cursor]!==NULL)$this->limit=(int)$this->args[$cursor];$cursor++;return'';}elseif($mod==='ofs'){if($this->args[$cursor]!==NULL)$this->offset=(int)$this->args[$cursor];$cursor++;return'';}else{$cursor++;return$this->formatValue($this->args[$cursor-1],$mod);}}if($this->comment)return'...';if($matches[1])return$this->identifiers->{$matches[1]};if($matches[2])return$this->identifiers->{$matches[2]};if($matches[3])return$this->driver->escape(str_replace("''","'",$matches[4]),dibi::TEXT);if($matches[5])return$this->driver->escape(str_replace('""','"',$matches[6]),dibi::TEXT);if($matches[7]){$this->hasError=TRUE;return'**Alone quote**';}if($matches[8]){$m=substr($matches[8],0,-1);$m=isset(dibi::$substs[$m])?dibi::$substs[$m]:call_user_func(dibi::$substFallBack,$m);return$matches[9]==''?$this->formatValue($m,FALSE):$m.$matches[9];}die('this should be never executed');}public
- function
- delimite($value){$value=self::substitute($value);$parts=explode('.',$value);foreach($parts
- as&$v){if($v!=='*')$v=$this->driver->escape($v,dibi::IDENTIFIER);}return
- implode('.',$parts);}public
- static
- function
- substitute($value){if(strpos($value,':')!==FALSE){return
- preg_replace_callback('#:([^:\s]*):#',array(__CLASS__,'subCb'),$value);}return$value;}private
- static
- function
- subCb($m){$m=$m[1];return
- isset(dibi::$substs[$m])?dibi::$substs[$m]:call_user_func(dibi::$substFallBack,$m);}}class
- DibiDataSource
- extends
- DibiObject
- implements
- IDataSource{private$connection;private$sql;private$result;private$count;private$totalCount;private$cols=array();private$sorting=array();private$conds=array();private$offset;private$limit;public
- function
- __construct($sql,DibiConnection$connection){if(strpbrk($sql," \t\r\n")===FALSE){$this->sql=$connection->getDriver()->escape($sql,dibi::IDENTIFIER);}else{$this->sql='('.$sql.') t';}$this->connection=$connection;}public
- function
- select($col,$as=NULL){if(is_array($col)){$this->cols=$col;}else{$this->cols[$col]=$as;}$this->result=NULL;return$this;}public
- function
- where($cond){if(is_array($cond)){$this->conds[]=$cond;}else{$this->conds[]=func_get_args();}$this->result=$this->count=NULL;return$this;}public
- function
- orderBy($row,$sorting='ASC'){if(is_array($row)){$this->sorting=$row;}else{$this->sorting[$row]=$sorting;}$this->result=NULL;return$this;}public
- function
- applyLimit($limit,$offset=NULL){$this->limit=$limit;$this->offset=$offset;$this->result=$this->count=NULL;return$this;}final
- public
- function
- getConnection(){return$this->connection;}public
- function
- getResult(){if($this->result===NULL){$this->result=$this->connection->nativeQuery($this->__toString());}return$this->result;}public
- function
- getIterator(){return$this->getResult()->getIterator();}public
- function
- fetch(){return$this->getResult()->fetch();}public
- function
- fetchSingle(){return$this->getResult()->fetchSingle();}public
- function
- fetchAll(){return$this->getResult()->fetchAll();}public
- function
- fetchAssoc($assoc){return$this->getResult()->fetchAssoc($assoc);}public
- function
- fetchPairs($key=NULL,$value=NULL){return$this->getResult()->fetchPairs($key,$value);}public
- function
- release(){$this->result=$this->count=$this->totalCount=NULL;}public
- function
- toFluent(){return$this->connection->select('*')->from('(%SQL) AS t',$this->__toString());}public
- function
- toDataSource(){return
- new
- self($this->__toString(),$this->connection);}public
- function
- __toString(){return$this->connection->translate('
- SELECT %n',(empty($this->cols)?'*':$this->cols),'
- FROM %SQL',$this->sql,'
- %ex',$this->conds?array('WHERE %and',$this->conds):NULL,'
- %ex',$this->sorting?array('ORDER BY %by',$this->sorting):NULL,'
- %ofs %lmt',$this->offset,$this->limit);}public
- function
- count(){if($this->count===NULL){$this->count=$this->conds||$this->offset||$this->limit?(int)$this->connection->nativeQuery('SELECT COUNT(*) FROM ('.$this->__toString().') AS t')->fetchSingle():$this->getTotalCount();}return$this->count;}public
- function
- getTotalCount(){if($this->totalCount===NULL){$this->totalCount=(int)$this->connection->nativeQuery('SELECT COUNT(*) FROM '.$this->sql)->fetchSingle();}return$this->totalCount;}}class
- DibiFluent
- extends
- DibiObject
- implements
- IDataSource{const
- REMOVE=FALSE;public
- static$masks=array('SELECT'=>array('SELECT','DISTINCT','FROM','WHERE','GROUP BY','HAVING','ORDER BY','LIMIT','OFFSET'),'UPDATE'=>array('UPDATE','SET','WHERE','ORDER BY','LIMIT'),'INSERT'=>array('INSERT','INTO','VALUES','SELECT'),'DELETE'=>array('DELETE','FROM','USING','WHERE','ORDER BY','LIMIT'));public
- static$modifiers=array('SELECT'=>'%n','FROM'=>'%n','IN'=>'%in','VALUES'=>'%l','SET'=>'%a','WHERE'=>'%and','HAVING'=>'%and','ORDER BY'=>'%by','GROUP BY'=>'%by');public
- static$separators=array('SELECT'=>',','FROM'=>',','WHERE'=>'AND','GROUP BY'=>',','HAVING'=>'AND','ORDER BY'=>',','LIMIT'=>FALSE,'OFFSET'=>FALSE,'SET'=>',','VALUES'=>',','INTO'=>FALSE);public
- static$clauseSwitches=array('JOIN'=>'FROM','INNER JOIN'=>'FROM','LEFT JOIN'=>'FROM','RIGHT JOIN'=>'FROM');private$connection;private$command;private$clauses=array();private$flags=array();private$cursor;private
- static$normalizer;public
- function
- __construct(DibiConnection$connection){$this->connection=$connection;if(self::$normalizer===NULL){self::$normalizer=new
- DibiLazyStorage(array(__CLASS__,'_formatClause'));}}public
- function
- __call($clause,$args){$clause=self::$normalizer->$clause;if($this->command===NULL){if(isset(self::$masks[$clause])){$this->clauses=array_fill_keys(self::$masks[$clause],NULL);}$this->cursor=&$this->clauses[$clause];$this->cursor=array();$this->command=$clause;}if(isset(self::$clauseSwitches[$clause])){$this->cursor=&$this->clauses[self::$clauseSwitches[$clause]];}if(array_key_exists($clause,$this->clauses)){$this->cursor=&$this->clauses[$clause];if($args===array(self::REMOVE)){$this->cursor=NULL;return$this;}if(isset(self::$separators[$clause])){$sep=self::$separators[$clause];if($sep===FALSE){$this->cursor=array();}elseif(!empty($this->cursor)){$this->cursor[]=$sep;}}}else{if($args===array(self::REMOVE)){return$this;}$this->cursor[]=$clause;}if($this->cursor===NULL){$this->cursor=array();}if(count($args)===1){$arg=$args[0];if($arg===TRUE){return$this;}elseif(is_string($arg)&&preg_match('#^[a-z:_][a-z0-9_.:]*$#i',$arg)){$args=array('%n',$arg);}elseif($arg
- instanceof
- self){$args=array_merge(array('('),$arg->_export(),array(')'));}elseif(is_array($arg)||$arg
- instanceof
- Traversable){if(isset(self::$modifiers[$clause])){$args=array(self::$modifiers[$clause],$arg);}elseif(is_string(key($arg))){$args=array('%a',$arg);}}}foreach($args
- as$arg)$this->cursor[]=$arg;return$this;}public
- function
- clause($clause,$remove=FALSE){$this->cursor=&$this->clauses[self::$normalizer->$clause];if($remove){trigger_error(__METHOD__.'(..., TRUE) is deprecated; use removeClause() instead.',E_USER_NOTICE);$this->cursor=NULL;}elseif($this->cursor===NULL){$this->cursor=array();}return$this;}public
- function
- removeClause($clause){$this->clauses[self::$normalizer->$clause]=NULL;return$this;}public
- function
- setFlag($flag,$value=TRUE){$flag=strtoupper($flag);if($value){$this->flags[$flag]=TRUE;}else{unset($this->flags[$flag]);}return$this;}final
- public
- function
- getFlag($flag){return
- isset($this->flags[strtoupper($flag)]);}final
- public
- function
- getCommand(){return$this->command;}final
- public
- function
- getConnection(){return$this->connection;}public
- function
- execute($return=NULL){$res=$this->connection->query($this->_export());return$return===dibi::IDENTIFIER?$this->connection->getInsertId():$res;}public
- function
- fetch(){if($this->command==='SELECT'){return$this->connection->query($this->_export(NULL,array('%lmt',1)))->fetch();}else{return$this->connection->query($this->_export())->fetch();}}public
- function
- fetchSingle(){if($this->command==='SELECT'){return$this->connection->query($this->_export(NULL,array('%lmt',1)))->fetchSingle();}else{return$this->connection->query($this->_export())->fetchSingle();}}public
- function
- fetchAll($offset=NULL,$limit=NULL){return$this->connection->query($this->_export(NULL,array('%ofs %lmt',$offset,$limit)))->fetchAll();}public
- function
- fetchAssoc($assoc){return$this->connection->query($this->_export())->fetchAssoc($assoc);}public
- function
- fetchPairs($key=NULL,$value=NULL){return$this->connection->query($this->_export())->fetchPairs($key,$value);}public
- function
- getIterator($offset=NULL,$limit=NULL){return$this->connection->query($this->_export(NULL,array('%ofs %lmt',$offset,$limit)))->getIterator();}public
- function
- test($clause=NULL){return$this->connection->test($this->_export($clause));}public
- function
- count(){return(int)$this->connection->query('SELECT COUNT(*) FROM (%ex',$this->_export(),') AS [data]')->fetchSingle();}public
- function
- toDataSource(){return
- new
- DibiDataSource($this->connection->translate($this->_export()),$this->connection);}final
- public
- function
- __toString(){return$this->connection->translate($this->_export());}protected
- function
- _export($clause=NULL,$args=array()){if($clause===NULL){$data=$this->clauses;}else{$clause=self::$normalizer->$clause;if(array_key_exists($clause,$this->clauses)){$data=array($clause=>$this->clauses[$clause]);}else{return
- array();}}foreach($data
- as$clause=>$statement){if($statement!==NULL){$args[]=$clause;if($clause===$this->command&&$this->flags){$args[]=implode(' ',array_keys($this->flags));}foreach($statement
- as$arg)$args[]=$arg;}}return$args;}public
- static
- function
- _formatClause($s){if($s==='order'||$s==='group'){$s.='By';trigger_error("Did you mean '$s'?",E_USER_NOTICE);}return
- strtoupper(preg_replace('#[a-z](?=[A-Z])#','$0 ',$s));}public
- function
- __clone(){foreach($this->clauses
- as$clause=>$val){$this->clauses[$clause]=&$val;unset($val);}$this->cursor=&$foo;}}class
- DibiDatabaseInfo
- extends
- DibiObject{private$reflector;private$name;private$tables;public
- function
- __construct(IDibiReflector$reflector,$name){$this->reflector=$reflector;$this->name=$name;}public
- function
- getName(){return$this->name;}public
- function
- getTables(){$this->init();return
- array_values($this->tables);}public
- function
- getTableNames(){$this->init();$res=array();foreach($this->tables
- as$table){$res[]=$table->getName();}return$res;}public
- function
- getTable($name){$name=DibiTranslator::substitute($name);$this->init();$l=strtolower($name);if(isset($this->tables[$l])){return$this->tables[$l];}else{throw
- new
- DibiException("Database '$this->name' has no table '$name'.");}}public
- function
- hasTable($name){$name=DibiTranslator::substitute($name);$this->init();return
- isset($this->tables[strtolower($name)]);}protected
- function
- init(){if($this->tables===NULL){$this->tables=array();foreach($this->reflector->getTables()as$info){$this->tables[strtolower($info['name'])]=new
- DibiTableInfo($this->reflector,$info);}}}}class
- DibiTableInfo
- extends
- DibiObject{private$reflector;private$name;private$view;private$columns;private$foreignKeys;private$indexes;private$primaryKey;public
- function
- __construct(IDibiReflector$reflector,array$info){$this->reflector=$reflector;$this->name=$info['name'];$this->view=!empty($info['view']);}public
- function
- getName(){return$this->name;}public
- function
- isView(){return$this->view;}public
- function
- getColumns(){$this->initColumns();return
- array_values($this->columns);}public
- function
- getColumnNames(){$this->initColumns();$res=array();foreach($this->columns
- as$column){$res[]=$column->getName();}return$res;}public
- function
- getColumn($name){$name=DibiTranslator::substitute($name);$this->initColumns();$l=strtolower($name);if(isset($this->columns[$l])){return$this->columns[$l];}else{throw
- new
- DibiException("Table '$this->name' has no column '$name'.");}}public
- function
- hasColumn($name){$name=DibiTranslator::substitute($name);$this->initColumns();return
- isset($this->columns[strtolower($name)]);}public
- function
- getForeignKeys(){$this->initForeignKeys();return$this->foreignKeys;}public
- function
- getIndexes(){$this->initIndexes();return$this->indexes;}public
- function
- getPrimaryKey(){$this->initIndexes();return$this->primaryKey;}protected
- function
- initColumns(){if($this->columns===NULL){$this->columns=array();foreach($this->reflector->getColumns($this->name)as$info){$this->columns[strtolower($info['name'])]=new
- DibiColumnInfo($this->reflector,$info);}}}protected
- function
- initIndexes(){if($this->indexes===NULL){$this->initColumns();$this->indexes=array();foreach($this->reflector->getIndexes($this->name)as$info){foreach($info['columns']as$key=>$name){$info['columns'][$key]=$this->columns[strtolower($name)];}$this->indexes[strtolower($info['name'])]=new
- DibiIndexInfo($info);if(!empty($info['primary'])){$this->primaryKey=$this->indexes[strtolower($info['name'])];}}}}protected
- function
- initForeignKeys(){throw
- new
- NotImplementedException;}}class
- DibiResultInfo
- extends
- DibiObject{private$driver;private$columns;private$names;public
- function
- __construct(IDibiResultDriver$driver){$this->driver=$driver;}public
- function
- getColumns(){$this->initColumns();return
- array_values($this->columns);}public
- function
- getColumnNames($fullNames=FALSE){$this->initColumns();$res=array();foreach($this->columns
- as$column){$res[]=$fullNames?$column->getFullName():$column->getName();}return$res;}public
- function
- getColumn($name){$name=DibiTranslator::substitute($name);$this->initColumns();$l=strtolower($name);if(isset($this->names[$l])){return$this->names[$l];}else{throw
- new
- DibiException("Result set has no column '$name'.");}}public
- function
- hasColumn($name){$name=DibiTranslator::substitute($name);$this->initColumns();return
- isset($this->names[strtolower($name)]);}protected
- function
- initColumns(){if($this->columns===NULL){$this->columns=array();$reflector=$this->driver
- instanceof
- IDibiReflector?$this->driver:NULL;foreach($this->driver->getResultColumns()as$info){$this->columns[]=$this->names[$info['name']]=new
- DibiColumnInfo($reflector,$info);}}}}class
- DibiColumnInfo
- extends
- DibiObject{private
- static$types;private$reflector;private$info;public
- function
- __construct(IDibiReflector$reflector=NULL,array$info){$this->reflector=$reflector;$this->info=$info;}public
- function
- getName(){return$this->info['name'];}public
- function
- getFullName(){return
- isset($this->info['fullname'])?$this->info['fullname']:NULL;}public
- function
- hasTable(){return!empty($this->info['table']);}public
- function
- getTable(){if(empty($this->info['table'])||!$this->reflector){throw
- new
- DibiException("Table is unknown or not available.");}return
- new
- DibiTableInfo($this->reflector,array('name'=>$this->info['table']));}public
- function
- getTableName(){return
- isset($this->info['table'])?$this->info['table']:NULL;}public
- function
- getType(){if(self::$types===NULL){self::$types=new
- DibiLazyStorage(array(__CLASS__,'detectType'));}return$this->info['nativetype']?self::$types->{$this->info['nativetype']}:dibi::TEXT;}public
- function
- getNativeType(){return$this->info['nativetype'];}public
- function
- getSize(){return
- isset($this->info['size'])?(int)$this->info['size']:NULL;}public
- function
- isUnsigned(){return
- isset($this->info['unsigned'])?(bool)$this->info['unsigned']:NULL;}public
- function
- isNullable(){return
- isset($this->info['nullable'])?(bool)$this->info['nullable']:NULL;}public
- function
- isAutoIncrement(){return
- isset($this->info['autoincrement'])?(bool)$this->info['autoincrement']:NULL;}public
- function
- getDefault(){return
- isset($this->info['default'])?$this->info['default']:NULL;}public
- function
- getVendorInfo($key){return
- isset($this->info['vendor'][$key])?$this->info['vendor'][$key]:NULL;}public
- static
- function
- detectType($type){static$patterns=array('BYTEA|BLOB|BIN'=>dibi::BINARY,'TEXT|CHAR|BIGINT|LONGLONG'=>dibi::TEXT,'BYTE|COUNTER|SERIAL|INT|LONG'=>dibi::INTEGER,'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER'=>dibi::FLOAT,'^TIME$'=>dibi::TIME,'TIME'=>dibi::DATETIME,'YEAR|DATE'=>dibi::DATE,'BOOL|BIT'=>dibi::BOOL);foreach($patterns
- as$s=>$val){if(preg_match("#$s#i",$type)){return$val;}}return
- dibi::TEXT;}}class
- DibiForeignKeyInfo
- extends
- DibiObject{private$name;private$references;public
- function
- __construct($name,array$references){$this->name=$name;$this->references=$references;}public
- function
- getName(){return$this->name;}public
- function
- getReferences(){return$this->references;}}class
- DibiIndexInfo
- extends
- DibiObject{private$info;public
- function
- __construct(array$info){$this->info=$info;}public
- function
- getName(){return$this->info['name'];}public
- function
- getColumns(){return$this->info['columns'];}public
- function
- isUnique(){return!empty($this->info['unique']);}public
- function
- isPrimary(){return!empty($this->info['primary']);}}class
- DibiProfiler
- extends
- DibiObject
- implements
- IDibiProfiler,IDebugPanel{static
- public$maxQueries=30;static
- public$maxLength=1000;private$file;public$useFirebug;public$explainQuery=TRUE;private$filter=self::ALL;public
- static$tickets=array();public
- static$fireTable=array(array('Time','SQL Statement','Rows','Connection'));public
- function
- __construct(array$config){if(class_exists('Debug',FALSE)&&is_callable('Debug::addPanel')){Debug::addPanel($this);}$this->useFirebug=isset($_SERVER['HTTP_USER_AGENT'])&&strpos($_SERVER['HTTP_USER_AGENT'],'FirePHP/');if(isset($config['filter'])){$this->setFilter($config['filter']);}if(isset($config['explain'])){$this->explainQuery=(bool)$config['explain'];}}pub…
Large files files are truncated, but you can click here to view the full file