/extlib/DB/DataObject.php
PHP | 4851 lines | 3030 code | 668 blank | 1153 comment | 582 complexity | 7101a9a262e1f720338ab63f667baf88 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, GPL-2.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Object Based Database Query Builder and data store
- *
- * For PHP versions 4,5 and 6
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Database
- * @package DB_DataObject
- * @author Alan Knowles <alan@akbkhome.com>
- * @copyright 1997-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: DataObject.php 329992 2013-04-03 11:38:43Z alan_k $
- * @link http://pear.php.net/package/DB_DataObject
- */
-
- /* ===========================================================================
- *
- * !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
- *
- * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
- * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
- * this file. reducing the optimization level may also solve the segfault.
- * ===========================================================================
- */
- /**
- * The main "DB_DataObject" class is really a base class for your own tables classes
- *
- * // Set up the class by creating an ini file (refer to the manual for more details
- * [DB_DataObject]
- * database = mysql:/username:password@host/database
- * schema_location = /home/myapplication/database
- * class_location = /home/myapplication/DBTables/
- * clase_prefix = DBTables_
- *
- *
- * //Start and initialize...................... - dont forget the &
- * $config = parse_ini_file('example.ini',true);
- * $options = &PEAR::getStaticProperty('DB_DataObject','options');
- * $options = $config['DB_DataObject'];
- *
- * // example of a class (that does not use the 'auto generated tables data')
- * class mytable extends DB_DataObject {
- * // mandatory - set the table
- * var $_database_dsn = "mysql://username:password@localhost/database";
- * var $__table = "mytable";
- * function table() {
- * return array(
- * 'id' => 1, // integer or number
- * 'name' => 2, // string
- * );
- * }
- * function keys() {
- * return array('id');
- * }
- * }
- *
- * // use in the application
- *
- *
- * Simple get one row
- *
- * $instance = new mytable;
- * $instance->get("id",12);
- * echo $instance->somedata;
- *
- *
- * Get multiple rows
- *
- * $instance = new mytable;
- * $instance->whereAdd("ID > 12");
- * $instance->whereAdd("ID < 14");
- * $instance->find();
- * while ($instance->fetch()) {
- * echo $instance->somedata;
- * }
- /**
- * Needed classes
- * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
- */
- require_once 'PEAR.php';
- /**
- * We are duping fetchmode constants to be compatible with
- * both DB and MDB2
- */
- define('DB_DATAOBJECT_FETCHMODE_ORDERED',1);
- define('DB_DATAOBJECT_FETCHMODE_ASSOC',2);
- /**
- * these are constants for the get_table array
- * user to determine what type of escaping is required around the object vars.
- */
- define('DB_DATAOBJECT_INT', 1); // does not require ''
- define('DB_DATAOBJECT_STR', 2); // requires ''
- define('DB_DATAOBJECT_DATE', 4); // is date #TODO
- define('DB_DATAOBJECT_TIME', 8); // is time #TODO
- define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
- define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
- define('DB_DATAOBJECT_BLOB', 64); // is blob type
- define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
- define('DB_DATAOBJECT_MYSQLTIMESTAMP' , 256); // mysql timestamps (ignored by update/insert)
- /*
- * Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
- */
- //define('DB_DATAOBJECT_NO_OVERLOAD',true)
- /**
- * Theses are the standard error codes, most methods will fail silently - and return false
- * to access the error message either use $table->_lastError
- * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
- * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
- */
- define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
- define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
- define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
- define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
- define('DB_DATAOBJECT_ERROR_INVALID_CALL' ,-7); // overlad getter/setter failure
- /**
- * Used in methods like delete() and count() to specify that the method should
- * build the condition only out of the whereAdd's and not the object parameters.
- */
- define('DB_DATAOBJECT_WHEREADD_ONLY', true);
- /**
- *
- * storage for connection and result objects,
- * it is done this way so that print_r()'ing the is smaller, and
- * it reduces the memory size of the object.
- * -- future versions may use $this->_connection = & PEAR object..
- * although will need speed tests to see how this affects it.
- * - includes sub arrays
- * - connections = md5 sum mapp to pear db object
- * - results = [id] => map to pear db object
- * - resultseq = sequence id for results & results field
- * - resultfields = [id] => list of fields return from query (for use with toArray())
- * - ini = mapping of database to ini file results
- * - links = mapping of database to links file
- * - lasterror = pear error objects for last error event.
- * - config = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
- * - array of loaded classes by autoload method - to stop it doing file access request over and over again!
- */
- $GLOBALS['_DB_DATAOBJECT']['RESULTS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
- $GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['INI'] = array();
- $GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
- $GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
- $GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
- $GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
- $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
- $GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
-
- // this will be horrifically slow!!!!
- // these two are BC/FC handlers for call in PHP4/5
-
- if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
-
- class DB_DataObject_Overload
- {
- function __call($method,$args)
- {
- $return = null;
- $this->_call($method,$args,$return);
- return $return;
- }
- function __sleep()
- {
- return array_keys(get_object_vars($this)) ;
- }
- }
- } else {
- class DB_DataObject_Overload {}
- }
-
-
- /*
- *
- * @package DB_DataObject
- * @author Alan Knowles <alan@akbkhome.com>
- * @since PHP 4.0
- */
-
- class DB_DataObject extends DB_DataObject_Overload
- {
- /**
- * The Version - use this to check feature changes
- *
- * @access private
- * @var string
- */
- var $_DB_DataObject_version = "1.11.0";
- /**
- * The Database table (used by table extends)
- *
- * @access private
- * @var string
- */
- var $__table = ''; // database table
- /**
- * The Number of rows returned from a query
- *
- * @access public
- * @var int
- */
- var $N = 0; // Number of rows returned from a query
- /* ============================================================= */
- /* Major Public Methods */
- /* (designed to be optionally then called with parent::method()) */
- /* ============================================================= */
- /**
- * Get a result using key, value.
- *
- * for example
- * $object->get("ID",1234);
- * Returns Number of rows located (usually 1) for success,
- * and puts all the table columns into this classes variables
- *
- * see the fetch example on how to extend this.
- *
- * if no value is entered, it is assumed that $key is a value
- * and get will then use the first key in keys()
- * to obtain the key.
- *
- * @param string $k column
- * @param string $v value
- * @access public
- * @return int No. of rows
- */
- function get($k = null, $v = null)
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- $keys = array();
-
- if ($v === null) {
- $v = $k;
- $keys = $this->keys();
- if (!$keys) {
- $this->raiseError("No Keys available for {$this->tableName()}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $k = $keys[0];
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$k $v " .print_r($keys,true), "GET");
- }
-
- if ($v === null) {
- $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- $this->$k = $v;
- return $this->find(1);
- }
-
- /**
- * Get the value of the primary id
- *
- * While I normally use 'id' as the PRIMARY KEY value, some database use
- * {table}_id as the column name.
- *
- * To save a bit of typing,
- *
- * $id = $do->pid();
- *
- * @return the id
- */
- function pid()
- {
- $keys = $this->keys();
- if (!$keys) {
- $this->raiseError("No Keys available for {$this->tableName()}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $k = $keys[0];
- if (empty($this->$k)) { // we do not
- $this->raiseError("pid() called on Object where primary key value not available",
- DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- return $this->$k;
- }
-
- /**
- * build the basic select query.
- *
- * @access private
- */
-
- function _build_select()
- {
- global $_DB_DATAOBJECT;
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- if ($quoteIdentifiers) {
- $this->_connect();
- $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- }
- $tn = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName()) ;
- if (!empty($this->_query['derive_table']) && !empty($this->_query['derive_select']) ) {
-
- // this is a derived select..
- // not much support in the api yet..
-
- $sql = 'SELECT ' .
- $this->_query['derive_select']
- .' FROM ( SELECT'.
- $this->_query['data_select'] . " \n" .
- " FROM $tn \n" .
- $this->_join . " \n" .
- $this->_query['condition'] . " \n" .
- $this->_query['group_by'] . " \n" .
- $this->_query['having'] . " \n" .
- ') ' . $this->_query['derive_table'];
-
- return $sql;
-
-
- }
-
-
-
- $sql = 'SELECT ' .
- $this->_query['data_select'] . " \n" .
- " FROM $tn \n" .
- $this->_join . " \n" .
- $this->_query['condition'] . " \n" .
- $this->_query['group_by'] . " \n" .
- $this->_query['having'] . " \n";
-
- return $sql;
- }
-
- /**
- * find results, either normal or crosstable
- *
- * for example
- *
- * $object = new mytable();
- * $object->ID = 1;
- * $object->find();
- *
- *
- * will set $object->N to number of rows, and expects next command to fetch rows
- * will return $object->N
- *
- * if an error occurs $object->N will be set to false and return value will also be false;
- * if numRows is not supported it will
- *
- *
- * @param boolean $n Fetch first result
- * @access public
- * @return mixed (number of rows returned, or true if numRows fetching is not supported)
- */
- function find($n = false)
- {
- global $_DB_DATAOBJECT;
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($n, "find",1);
- }
- if (!$this->__table) {
- // xdebug can backtrace this!
- trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
- }
- $this->N = 0;
- $query_before = $this->_query;
- $this->_build_condition($this->table()) ;
-
-
- $this->_connect();
- $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
-
- $sql = $this->_build_select();
-
- foreach ($this->_query['unions'] as $union_ar) {
- $sql .= $union_ar[1] . $union_ar[0]->_build_select() . " \n";
- }
-
- $sql .= $this->_query['order_by'] . " \n";
-
-
- /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
- if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
- ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
- /* PEAR DB specific */
-
- if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
- $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
- }
- } else {
- /* theoretically MDB2! */
- if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
- $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
- }
- }
-
-
- $err = $this->_query($sql);
- if (is_a($err,'PEAR_Error')) {
- return false;
- }
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("CHECK autofetchd $n", "find", 1);
- }
-
- // find(true)
-
- $ret = $this->N;
- if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
- // clear up memory if nothing found!?
- unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
- }
-
- if ($n && $this->N > 0 ) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("ABOUT TO AUTOFETCH", "find", 1);
- }
- $fs = $this->fetch();
- // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
- // - hence find() also returns false..
- $ret = ($ret === true) ? $fs : $ret;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("DONE", "find", 1);
- }
- $this->_query = $query_before;
- return $ret;
- }
- /**
- * fetches next row into this objects var's
- *
- * returns 1 on success 0 on failure
- *
- *
- *
- * Example
- * $object = new mytable();
- * $object->name = "fred";
- * $object->find();
- * $store = array();
- * while ($object->fetch()) {
- * echo $this->ID;
- * $store[] = $object; // builds an array of object lines.
- * }
- *
- * to add features to a fetch
- * function fetch () {
- * $ret = parent::fetch();
- * $this->date_formated = date('dmY',$this->date);
- * return $ret;
- * }
- *
- * @access public
- * @return boolean on success
- */
- function fetch()
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- if (empty($this->N)) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
- }
- return false;
- }
-
- if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
- !is_object($result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
- {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug('fetched on object after fetch completed (no results found)');
- }
- return false;
- }
-
-
- $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($array),"FETCH");
- }
-
- // fetched after last row..
- if ($array === null) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $t= explode(' ',microtime());
-
- $this->debug("Last Data Fetch'ed after " .
- ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
- " seconds",
- "FETCH", 1);
- }
- // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
- unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
-
- // we need to keep a copy of resultfields locally so toArray() still works
- // however we dont want to keep it in the global cache..
-
- if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
- $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
- unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
- }
- // this is probably end of data!!
- //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- // make sure resultFields is always empty..
- $this->_resultFields = false;
-
- if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
- // note: we dont declare this to keep the print_r size down.
- $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
- }
- $replace = array('.', ' ');
- foreach($array as $k=>$v) {
- // use strpos as str_replace is slow.
- $kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
- $k : str_replace($replace, '_', $k);
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
- }
- $this->$kk = $array[$k];
- }
-
- // set link flag
- $this->_link_loaded=false;
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->tableName()} DONE", "fetchrow",2);
- }
- if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
- $this->_query = false;
- }
- return true;
- }
-
- /**
- * fetches all results as an array,
- *
- * return format is dependant on args.
- * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
- *
- * A) Array of values (eg. a list of 'id')
- *
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1')
- * $ar = $x->fetchAll('id');
- * -- returns array(1,2,3,4,5)
- *
- * B) Array of values (not from table)
- *
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1');
- * $x->selectAdd();
- * $x->selectAdd('distinct(group_id) as group_id');
- * $ar = $x->fetchAll('group_id');
- * -- returns array(1,2,3,4,5)
- * *
- * C) A key=>value associative array
- *
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1')
- * $ar = $x->fetchAll('id','name');
- * -- returns array(1=>'fred',2=>'blogs',3=> .......
- *
- * D) array of objects
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1');
- * $ar = $x->fetchAll();
- *
- * E) array of arrays (for example)
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1');
- * $ar = $x->fetchAll(false,false,'toArray');
- *
- *
- * @param string|false $k key
- * @param string|false $v value
- * @param string|false $method method to call on each result to get array value (eg. 'toArray')
- * @access public
- * @return array format dependant on arguments, may be empty
- */
- function fetchAll($k= false, $v = false, $method = false)
- {
- // should it even do this!!!?!?
- if ($k !== false &&
- ( // only do this is we have not been explicit..
- empty($this->_query['data_select']) ||
- ($this->_query['data_select'] == '*')
- )
- ) {
- $this->selectAdd();
- $this->selectAdd($k);
- if ($v !== false) {
- $this->selectAdd($v);
- }
- }
-
- $this->find();
- $ret = array();
- while ($this->fetch()) {
- if ($v !== false) {
- $ret[$this->$k] = $this->$v;
- continue;
- }
- $ret[] = $k === false ?
- ($method == false ? clone($this) : $this->$method())
- : $this->$k;
- }
- return $ret;
-
- }
-
-
- /**
- * Adds a condition to the WHERE statement, defaults to AND
- *
- * $object->whereAdd(); //reset or cleaer ewhwer
- * $object->whereAdd("ID > 20");
- * $object->whereAdd("age > 20","OR");
- *
- * @param string $cond condition
- * @param string $logic optional logic "OR" (defaults to "AND")
- * @access public
- * @return string|PEAR::Error - previous condition or Error when invalid args found
- */
- function whereAdd($cond = false, $logic = 'AND')
- {
- // for PHP5.2.3 - there is a bug with setting array properties of an object.
- $_query = $this->_query;
-
- if (!isset($this->_query) || ($_query === false)) {
- return $this->raiseError(
- "You cannot do two queries on the same object (clone it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if ($cond === false) {
- $r = $this->_query['condition'];
- $_query['condition'] = '';
- $this->_query = $_query;
- return preg_replace('/^\s+WHERE\s+/','',$r);
- }
- // check input...= 0 or ' ' == error!
- if (!trim($cond)) {
- return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- $r = $_query['condition'];
- if ($_query['condition']) {
- $_query['condition'] .= " {$logic} ( {$cond} )";
- $this->_query = $_query;
- return $r;
- }
- $_query['condition'] = " WHERE ( {$cond} ) ";
- $this->_query = $_query;
- return $r;
- }
- /**
- * Adds a 'IN' condition to the WHERE statement
- *
- * $object->whereAddIn('id', $array, 'int'); //minimal usage
- * $object->whereAddIn('price', $array, 'float', 'OR'); // cast to float, and call whereAdd with 'OR'
- * $object->whereAddIn('name', $array, 'string'); // quote strings
- *
- * @param string $key key column to match
- * @param array $list list of values to match
- * @param string $type string|int|integer|float|bool cast to type.
- * @param string $logic optional logic to call whereAdd with eg. "OR" (defaults to "AND")
- * @access public
- * @return string|PEAR::Error - previous condition or Error when invalid args found
- */
- function whereAddIn($key, $list, $type, $logic = 'AND')
- {
- $not = '';
- if ($key[0] == '!') {
- $not = 'NOT ';
- $key = substr($key, 1);
- }
- // fix type for short entry.
- $type = $type == 'int' ? 'integer' : $type;
- if ($type == 'string') {
- $this->_connect();
- }
- $ar = array();
- foreach($list as $k) {
- settype($k, $type);
- $ar[] = $type == 'string' ? $this->_quote($k) : $k;
- }
-
- if (!$ar) {
- return $not ? $this->_query['condition'] : $this->whereAdd("1=0");
- }
- return $this->whereAdd("$key $not IN (". implode(',', $ar). ')', $logic );
- }
-
-
- /**
- * Adds a order by condition
- *
- * $object->orderBy(); //clears order by
- * $object->orderBy("ID");
- * $object->orderBy("ID,age");
- *
- * @param string $order Order
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function orderBy($order = false)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($order === false) {
- $this->_query['order_by'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($order)) {
- return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if (!$this->_query['order_by']) {
- $this->_query['order_by'] = " ORDER BY {$order} ";
- return;
- }
- $this->_query['order_by'] .= " , {$order}";
- }
- /**
- * Adds a group by condition
- *
- * $object->groupBy(); //reset the grouping
- * $object->groupBy("ID DESC");
- * $object->groupBy("ID,age");
- *
- * @param string $group Grouping
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function groupBy($group = false)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($group === false) {
- $this->_query['group_by'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($group)) {
- return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
-
- if (!$this->_query['group_by']) {
- $this->_query['group_by'] = " GROUP BY {$group} ";
- return;
- }
- $this->_query['group_by'] .= " , {$group}";
- }
- /**
- * Adds a having clause
- *
- * $object->having(); //reset the grouping
- * $object->having("sum(value) > 0 ");
- *
- * @param string $having condition
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function having($having = false)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($having === false) {
- $this->_query['having'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($having)) {
- return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
-
- if (!$this->_query['having']) {
- $this->_query['having'] = " HAVING {$having} ";
- return;
- }
- $this->_query['having'] .= " AND {$having}";
- }
- /**
- * Sets the Limit
- *
- * $boject->limit(); // clear limit
- * $object->limit(12);
- * $object->limit(12,10);
- *
- * Note this will emit an error on databases other than mysql/postgress
- * as there is no 'clean way' to implement it. - you should consider refering to
- * your database manual to decide how you want to implement it.
- *
- * @param string $a limit start (or number), or blank to reset
- * @param string $b number
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function limit($a = null, $b = null)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if ($a === null) {
- $this->_query['limit_start'] = '';
- $this->_query['limit_count'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
- || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
- return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- global $_DB_DATAOBJECT;
- $this->_connect();
- $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
- $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
-
- }
- /**
- * Adds a select columns
- *
- * $object->selectAdd(); // resets select to nothing!
- * $object->selectAdd("*"); // default select
- * $object->selectAdd("unixtime(DATE) as udate");
- * $object->selectAdd("DATE");
- *
- * to prepend distict:
- * $object->selectAdd('distinct ' . $object->selectAdd());
- *
- * @param string $k
- * @access public
- * @return mixed null or old string if you reset it.
- */
- function selectAdd($k = null)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($k === null) {
- $old = $this->_query['data_select'];
- $this->_query['data_select'] = '';
- return $old;
- }
-
- // check input...= 0 or ' ' == error!
- if (!trim($k)) {
- return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if ($this->_query['data_select']) {
- $this->_query['data_select'] .= ', ';
- }
- $this->_query['data_select'] .= " $k ";
- }
- /**
- * Adds multiple Columns or objects to select with formating.
- *
- * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
- * // note with null it will also clear the '*' default select
- * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
- * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
- * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
- * objectTableName.colnameA as prefix_colnameA
- *
- * @param array|object|null the array or object to take column names from.
- * @param string format in sprintf format (use %s for the colname)
- * @param string table name eg. if you have joinAdd'd or send $from as an array.
- * @access public
- * @return void
- */
- function selectAs($from = null,$format = '%s',$tableName=false)
- {
- global $_DB_DATAOBJECT;
-
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if ($from === null) {
- // blank the '*'
- $this->selectAdd();
- $from = $this;
- }
-
-
- $table = $this->tableName();
- if (is_object($from)) {
- $table = $from->tableName();
- $from = array_keys($from->table());
- }
-
- if ($tableName !== false) {
- $table = $tableName;
- }
- $s = '%s';
- if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
- $this->_connect();
- $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $s = $DB->quoteIdentifier($s);
- $format = $DB->quoteIdentifier($format);
- }
- foreach ($from as $k) {
- $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
- }
- $this->_query['data_select'] .= "\n";
- }
- /**
- * Insert the current objects variables into the database
- *
- * Returns the ID of the inserted element (if auto increment or sequences are used.)
- *
- * for example
- *
- * Designed to be extended
- *
- * $object = new mytable();
- * $object->name = "fred";
- * echo $object->insert();
- *
- * @access public
- * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
- */
- function insert()
- {
- global $_DB_DATAOBJECT;
-
- // we need to write to the connection (For nextid) - so us the real
- // one not, a copyied on (as ret-by-ref fails with overload!)
-
- if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- $this->_connect();
- }
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $items = $this->table();
-
- if (!$items) {
- $this->raiseError("insert:No table definition for {$this->tableName()}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $options = $_DB_DATAOBJECT['CONFIG'];
- $datasaved = 1;
- $leftq = '';
- $rightq = '';
-
- $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]) ?
- $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] :
- $this->sequenceKey();
-
- $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
- $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
- $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
-
- $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
-
-
- // nativeSequences or Sequences..
- // big check for using sequences
-
- if (($key !== false) && !$useNative) {
-
- if (!$seq) {
- $keyvalue = $DB->nextId($this->tableName());
- } else {
- $f = $DB->getOption('seqname_format');
- $DB->setOption('seqname_format','%s');
- $keyvalue = $DB->nextId($seq);
- $DB->setOption('seqname_format',$f);
- }
- if (PEAR::isError($keyvalue)) {
- $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $this->$key = $keyvalue;
- }
-
- // if we haven't set disable_null_strings to "full"
- $ignore_null = !isset($options['disable_null_strings'])
- || !is_string($options['disable_null_strings'])
- || strtolower($options['disable_null_strings']) !== 'full' ;
-
-
- foreach($items as $k => $v) {
-
- // if we are using autoincrement - skip the column...
- if ($key && ($k == $key) && $useNative) {
- continue;
- }
-
-
-
-
- // Ignore variables which aren't set to a value
- if ( !isset($this->$k) && $ignore_null) {
- continue;
- }
- // dont insert data into mysql timestamps
- // use query() if you really want to do this!!!!
- if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
- continue;
- }
-
- if ($leftq) {
- $leftq .= ', ';
- $rightq .= ', ';
- }
-
- $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
-
- if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
- $value = $this->$k->toString($v,$DB);
- if (PEAR::isError($value)) {
- $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- $rightq .= $value;
- continue;
- }
-
-
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
- $rightq .= " NULL ";
- continue;
- }
- // DATE is empty... on a col. that can be null..
- // note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
- !($v & DB_DATAOBJECT_NOTNULL)) {
-
- $rightq .= " NULL ";
- continue;
- }
-
-
- if ($v & DB_DATAOBJECT_STR) {
- $rightq .= $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
- // use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
- $this->$k
- )) . " ";
- continue;
- }
- if (is_numeric($this->$k)) {
- $rightq .=" {$this->$k} ";
- continue;
- }
- /* flag up string values - only at debug level... !!!??? */
- if (is_object($this->$k) || is_array($this->$k)) {
- $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k,true),'ERROR');
- }
-
- // at present we only cast to integers
- // - V2 may store additional data about float/int
- $rightq .= ' ' . intval($this->$k) . ' ';
- }
-
- // not sure why we let empty insert here.. - I guess to generate a blank row..
-
-
- if ($leftq || $useNative) {
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
-
-
- if (($dbtype == 'pgsql') && empty($leftq)) {
- $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
- } else {
- $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
- }
-
-
-
-
- if (PEAR::isError($r)) {
- $this->raiseError($r);
- return false;
- }
-
- if ($r < 1) {
- return 0;
- }
-
-
- // now do we have an integer key!
-
- if ($key && $useNative) {
- switch ($dbtype) {
- case 'mysql':
- case 'mysqli':
- $method = "{$dbtype}_insert_id";
- $this->$key = $method(
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
- );
- break;
-
- case 'mssql':
- // note this is not really thread safe - you should wrapp it with
- // transactions = eg.
- // $db->query('BEGIN');
- // $db->insert();
- // $db->query('COMMIT');
- $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
- $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
- $mssql_key = $DB->$method("SELECT @@IDENTITY");
- if (PEAR::isError($mssql_key)) {
- $this->raiseError($mssql_key);
- return false;
- }
- $this->$key = $mssql_key;
- break;
-
- case 'pgsql':
- if (!$seq) {
- $seq = $DB->getSequenceName(strtolower($this->tableName()));
- }
- $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
- $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
- $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
- if (PEAR::isError($pgsql_key)) {
- $this->raiseError($pgsql_key);
- return false;
- }
- $this->$key = $pgsql_key;
- break;
-
- case 'ifx':
- $this->$key = array_shift (
- ifx_fetch_row (
- ifx_query(
- "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
- IFX_SCROLL
- ),
- "FIRST"
- )
- );
- break;
-
- }
-
- }
- if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
- $this->_clear_cache();
- }
- if ($key) {
- return $this->$key;
- }
- return true;
- }
- $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- /**
- * Updates current objects variables into the database
- * uses the keys() to decide how to update
- * Returns the true on success
- *
- * for example
- *
- * $object = DB_DataObject::factory('mytable');
- * $object->get("ID",234);
- * $object->email="testing@test.com";
- * if(!$object->update())
- * echo "UPDATE FAILED";
- *
- * to only update changed items :
- * $dataobject->get(132);
- * $original = $dataobject; // clone/copy it..
- * $dataobject->setFrom($_POST);
- * if ($dataobject->validate()) {
- * $dataobject->update($original);
- * } // otherwise an error...
- *
- * performing global updates:
- * $object = DB_DataObject::factory('mytable');
- * $object->status = "dead";
- * $object->whereAdd('age > 150');
- * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
- *
- * @param object dataobject (optional) | DB_DATAOBJECT_WHEREADD_ONLY - used to only update changed items.
- * @access public
- * @return int rows affected or false on failure
- */
- function update($dataObject = false)
- {
- global $_DB_DATAOBJECT;
- // connect will load the config!
- $this->_connect();
-
-
- $original_query = $this->_query;
-
- $items = $this->table();
-
- // only apply update against sequence key if it is set?????
-
- $seq = $this->sequenceKey();
- if ($seq[0] !== false) {
- $keys = array($seq[0]);
- if (!isset($this->{$keys[0]}) && $dataObject !== true) {
- $this->raiseError("update: trying to perform an update without
- the key set, and argument to update is not
- DB_DATAOBJECT_WHEREADD_ONLY
- ", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- } else {
- $keys = $this->keys();
- }
-
-
- if (!$items) {
- $this->raiseError("update:No table definition for {$this->tableName()}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $datasaved = 1;
- $settings = '';
- $this->_connect();
-
- $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $dbtype = $DB->dsn["phptype"];
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- $options = $_DB_DATAOBJECT['CONFIG'];
-
-
- $ignore_null = !isset($options['disable_null_strings'])
- || !is_string($options['disable_null_strings'])
- || strtolower($options['disable_null_strings']) !== 'full' ;
-
-
- foreach($items as $k => $v) {
-
- if (!isset($this->$k) && $ignore_null) {
- continue;
- }
- // ignore stuff thats
-
- // dont write things that havent changed..
- if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
- continue;
- }
-
- // - dont write keys to left.!!!
- if (in_array($k,$keys)) {
- continue;
- }
-
- // dont insert data into mysql timestamps
- // use query() if you really want to do this!!!!
- if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
- continue;
- }
-
-
- if ($settings) {
- $settings .= ', ';
- }
-
- $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
-
- if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
- $value = $this->$k->toString($v,$DB);
- if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
- return false;
- }
- $settings .= "$kSql = $value ";
- continue;
- }
-
- // special values ... at least null is handled...
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
- $settings .= "$kSql = NULL ";
- continue;
- }
- // DATE is empty... on a col. that can be null..
- // note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
- !($v & DB_DATAOBJECT_NOTNULL)) {
-
- $settings .= "$kSql = NULL ";
- continue;
- }
-
- if ($v & DB_DATAOBJECT_STR) {
- $settings .= "$kSql = ". $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
- // use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
- $this->$k
- )) . ' ';
- continue;
- }
- if (is_numeric($this->$k)) {
- $settings .= "$kSql = {$this->$k} ";
- continue;
- }
- // at present we only cast to integers
- // - V2 may store additional data about float/int
- $settings .= "$kSql = " . intval($this->$k) . ' ';
- }
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("got keys as ".serialize($keys),3);
- }
- if ($dataObject !== true) {
- $this->_build_condition($items,$keys);
- } else {
- // prevent wiping out of data!
- if (empty($this->_query['condition'])) {
- $this->raiseError("update: global table update not available
- do \$do->whereAdd('1=1'); if you really want to do that.
- ", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- }
-
-
-
- // echo " $settings, $this->condition ";
- if ($settings && isset($this->_query) && $this->_query['condition']) {
-
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
-
- $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
-
- // restore original query conditions.
- $this->_query = $original_query;
-
- if (PEAR::isError($r)) {
- $this-…
Large files files are truncated, but you can click here to view the full file