3 * Object Based Database Query Builder and data store
5 * For PHP versions 4,5 and 6
7 * LICENSE: This source file is subject to version 3.01 of the PHP license
8 * that is available through the world-wide-web at the following URI:
9 * http://www.php.net/license/3_01.txt. If you did not receive a copy of
10 * the PHP License and are unable to obtain it through the web, please
11 * send a note to license@php.net so we can mail you a copy immediately.
14 * @package DB_DataObject
15 * @author Alan Knowles <alan@akbkhome.com>
16 * @copyright 1997-2006 The PHP Group
17 * @license http://www.php.net/license/3_01.txt PHP License 3.01
18 * @version CVS: $Id: DataObject.php 301030 2010-07-07 02:26:31Z alan_k $
19 * @link http://pear.php.net/package/DB_DataObject
23 /* ===========================================================================
25 * !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
27 * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
28 * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
29 * this file. reducing the optimization level may also solve the segfault.
30 * ===========================================================================
34 * The main "DB_DataObject" class is really a base class for your own tables classes
36 * // Set up the class by creating an ini file (refer to the manual for more details
38 * database = mysql:/username:password@host/database
39 * schema_location = /home/myapplication/database
40 * class_location = /home/myapplication/DBTables/
41 * clase_prefix = DBTables_
44 * //Start and initialize...................... - dont forget the &
45 * $config = parse_ini_file('example.ini',true);
46 * $options = &PEAR::getStaticProperty('DB_DataObject','options');
47 * $options = $config['DB_DataObject'];
49 * // example of a class (that does not use the 'auto generated tables data')
50 * class mytable extends DB_DataObject {
51 * // mandatory - set the table
52 * var $_database_dsn = "mysql://username:password@localhost/database";
53 * var $__table = "mytable";
56 * 'id' => 1, // integer or number
57 * 'name' => 2, // string
65 * // use in the application
70 * $instance = new mytable;
71 * $instance->get("id",12);
72 * echo $instance->somedata;
77 * $instance = new mytable;
78 * $instance->whereAdd("ID > 12");
79 * $instance->whereAdd("ID < 14");
81 * while ($instance->fetch()) {
82 * echo $instance->somedata;
88 * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
91 require_once 'PEAR.php';
94 * We are duping fetchmode constants to be compatible with
97 define('DB_DATAOBJECT_FETCHMODE_ORDERED',1);
98 define('DB_DATAOBJECT_FETCHMODE_ASSOC',2);
105 * these are constants for the get_table array
106 * user to determine what type of escaping is required around the object vars.
108 define('DB_DATAOBJECT_INT', 1); // does not require ''
109 define('DB_DATAOBJECT_STR', 2); // requires ''
111 define('DB_DATAOBJECT_DATE', 4); // is date #TODO
112 define('DB_DATAOBJECT_TIME', 8); // is time #TODO
113 define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
114 define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
115 define('DB_DATAOBJECT_BLOB', 64); // is blob type
118 define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
119 define('DB_DATAOBJECT_MYSQLTIMESTAMP' , 256); // mysql timestamps (ignored by update/insert)
121 * Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
123 //define('DB_DATAOBJECT_NO_OVERLOAD',true)
127 * Theses are the standard error codes, most methods will fail silently - and return false
128 * to access the error message either use $table->_lastError
129 * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
130 * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
133 define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
134 define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
135 define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
136 define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
137 define('DB_DATAOBJECT_ERROR_INVALID_CALL' ,-7); // overlad getter/setter failure
140 * Used in methods like delete() and count() to specify that the method should
141 * build the condition only out of the whereAdd's and not the object parameters.
143 define('DB_DATAOBJECT_WHEREADD_ONLY', true);
147 * storage for connection and result objects,
148 * it is done this way so that print_r()'ing the is smaller, and
149 * it reduces the memory size of the object.
150 * -- future versions may use $this->_connection = & PEAR object..
151 * although will need speed tests to see how this affects it.
152 * - includes sub arrays
153 * - connections = md5 sum mapp to pear db object
154 * - results = [id] => map to pear db object
155 * - resultseq = sequence id for results & results field
156 * - resultfields = [id] => list of fields return from query (for use with toArray())
157 * - ini = mapping of database to ini file results
158 * - links = mapping of database to links file
159 * - lasterror = pear error objects for last error event.
160 * - config = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
161 * - array of loaded classes by autoload method - to stop it doing file access request over and over again!
163 $GLOBALS['_DB_DATAOBJECT']['RESULTS'] = array();
164 $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
165 $GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
166 $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
167 $GLOBALS['_DB_DATAOBJECT']['INI'] = array();
168 $GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
169 $GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
170 $GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
171 $GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
172 $GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
173 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
174 $GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
178 // this will be horrifically slow!!!!
179 // NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer (see define before..)
180 // these two are BC/FC handlers for call in PHP4/5
182 if ( substr(phpversion(),0,1) == 5) {
183 class DB_DataObject_Overload
185 function __call($method,$args)
188 $this->_call($method,$args,$return);
193 return array_keys(get_object_vars($this)) ;
197 if (version_compare(phpversion(),'4.3.10','eq') && !defined('DB_DATAOBJECT_NO_OVERLOAD')) {
199 "overload does not work with PHP4.3.10, either upgrade
200 (snaps.php.net) or more recent version
201 or define DB_DATAOBJECT_NO_OVERLOAD as per the manual.
205 if (!function_exists('clone')) {
206 // emulate clone - as per php_compact, slow but really the correct behaviour..
207 eval('function clone($t) { $r = $t; if (method_exists($r,"__clone")) { $r->__clone(); } return $r; }');
210 class DB_DataObject_Overload {
211 function __call($method,$args,&$return) {
212 return $this->_call($method,$args,$return);
225 * @package DB_DataObject
226 * @author Alan Knowles <alan@akbkhome.com>
230 class DB_DataObject extends DB_DataObject_Overload
233 * The Version - use this to check feature changes
238 var $_DB_DataObject_version = "1.9.5";
241 * The Database table (used by table extends)
246 var $__table = ''; // database table
249 * The Number of rows returned from a query
254 var $N = 0; // Number of rows returned from a query
256 /* ============================================================= */
257 /* Major Public Methods */
258 /* (designed to be optionally then called with parent::method()) */
259 /* ============================================================= */
263 * Get a result using key, value.
266 * $object->get("ID",1234);
267 * Returns Number of rows located (usually 1) for success,
268 * and puts all the table columns into this classes variables
270 * see the fetch example on how to extend this.
272 * if no value is entered, it is assumed that $key is a value
273 * and get will then use the first key in keys()
276 * @param string $k column
277 * @param string $v value
279 * @return int No. of rows
281 function get($k = null, $v = null)
283 global $_DB_DATAOBJECT;
284 if (empty($_DB_DATAOBJECT['CONFIG'])) {
285 DB_DataObject::_loadConfig();
291 $keys = $this->keys();
293 $this->raiseError("No Keys available for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
298 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
299 $this->debug("$k $v " .print_r($keys,true), "GET");
303 $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
307 return $this->find(1);
311 * An autoloading, caching static get method using key, value (based on get)
312 * (depreciated - use ::get / and your own caching method)
315 * $object = DB_DataObject::staticGet("DbTable_mytable",12);
317 * $object = DB_DataObject::staticGet("DbTable_mytable","name","fred");
319 * or write it into your extended class:
320 * function &staticGet($k,$v=NULL) { return DB_DataObject::staticGet("This_Class",$k,$v); }
322 * @param string $class class name
323 * @param string $k column (or value if using keys)
324 * @param string $v value (optional)
328 function &staticGet($class, $k, $v = null)
330 $lclass = strtolower($class);
331 global $_DB_DATAOBJECT;
332 if (empty($_DB_DATAOBJECT['CONFIG'])) {
333 DB_DataObject::_loadConfig();
342 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
343 DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
345 if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
346 return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
348 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
349 DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
352 $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
353 if (PEAR::isError($obj)) {
354 DB_DataObject::raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
359 if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
360 $_DB_DATAOBJECT['CACHE'][$lclass] = array();
362 if (!$obj->get($k,$v)) {
363 DB_DataObject::raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
368 $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
369 return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
373 * build the basic select query.
378 function _build_select()
380 global $_DB_DATAOBJECT;
381 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
382 if ($quoteIdentifiers) {
384 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
387 $this->_query['data_select'] . " \n" .
388 ' FROM ' . ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table) . " \n" .
389 $this->_join . " \n" .
390 $this->_query['condition'] . " \n" .
391 $this->_query['group_by'] . " \n" .
392 $this->_query['having'] . " \n";
399 * find results, either normal or crosstable
403 * $object = new mytable();
408 * will set $object->N to number of rows, and expects next command to fetch rows
409 * will return $object->N
411 * @param boolean $n Fetch first result
413 * @return mixed (number of rows returned, or true if numRows fetching is not supported)
415 function find($n = false)
417 global $_DB_DATAOBJECT;
418 if ($this->_query === false) {
420 "You cannot do two queries on the same object (copy it before finding)",
421 DB_DATAOBJECT_ERROR_INVALIDARGS);
425 if (empty($_DB_DATAOBJECT['CONFIG'])) {
426 DB_DataObject::_loadConfig();
429 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
430 $this->debug($n, "find",1);
432 if (!$this->__table) {
433 // xdebug can backtrace this!
434 trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
437 $query_before = $this->_query;
438 $this->_build_condition($this->table()) ;
442 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
445 $sql = $this->_build_select();
447 foreach ($this->_query['unions'] as $union_ar) {
448 $sql .= $union_ar[1] . $union_ar[0]->_build_select() . " \n";
451 $sql .= $this->_query['order_by'] . " \n";
454 /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
455 if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
456 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
457 /* PEAR DB specific */
459 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
460 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
463 /* theoretically MDB2! */
464 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
465 $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
472 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
473 $this->debug("CHECK autofetchd $n", "find", 1);
479 if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
480 // clear up memory if nothing found!?
481 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
484 if ($n && $this->N > 0 ) {
485 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
486 $this->debug("ABOUT TO AUTOFETCH", "find", 1);
488 $fs = $this->fetch();
489 // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
490 // - hence find() also returns false..
491 $ret = ($ret === true) ? $fs : $ret;
493 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
494 $this->debug("DONE", "find", 1);
496 $this->_query = $query_before;
501 * fetches next row into this objects var's
503 * returns 1 on success 0 on failure
508 * $object = new mytable();
509 * $object->name = "fred";
512 * while ($object->fetch()) {
514 * $store[] = $object; // builds an array of object lines.
517 * to add features to a fetch
518 * function fetch () {
519 * $ret = parent::fetch();
520 * $this->date_formated = date('dmY',$this->date);
525 * @return boolean on success
530 global $_DB_DATAOBJECT;
531 if (empty($_DB_DATAOBJECT['CONFIG'])) {
532 DB_DataObject::_loadConfig();
534 if (empty($this->N)) {
535 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
536 $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
541 if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
542 !is_object($result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
544 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
545 $this->debug('fetched on object after fetch completed (no results found)');
551 $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
552 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
553 $this->debug(serialize($array),"FETCH");
556 // fetched after last row..
557 if ($array === null) {
558 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
559 $t= explode(' ',microtime());
561 $this->debug("Last Data Fetch'ed after " .
562 ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
566 // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
567 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
569 // we need to keep a copy of resultfields locally so toArray() still works
570 // however we dont want to keep it in the global cache..
572 if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
573 $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
574 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
576 // this is probably end of data!!
577 //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
580 // make sure resultFields is always empty..
581 $this->_resultFields = false;
583 if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
584 // note: we dont declare this to keep the print_r size down.
585 $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
588 foreach($array as $k=>$v) {
589 $kk = str_replace(".", "_", $k);
590 $kk = str_replace(" ", "_", $kk);
591 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
592 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
594 $this->$kk = $array[$k];
598 $this->_link_loaded=false;
599 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
600 $this->debug("{$this->__table} DONE", "fetchrow",2);
602 if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
603 $this->_query = false;
610 * fetches all results as an array,
612 * return format is dependant on args.
613 * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
615 * A) Array of values (eg. a list of 'id')
617 * $x = DB_DataObject::factory('mytable');
618 * $x->whereAdd('something = 1')
619 * $ar = $x->fetchAll('id');
620 * -- returns array(1,2,3,4,5)
622 * B) Array of values (not from table)
624 * $x = DB_DataObject::factory('mytable');
625 * $x->whereAdd('something = 1');
627 * $x->selectAdd('distinct(group_id) as group_id');
628 * $ar = $x->fetchAll('group_id');
629 * -- returns array(1,2,3,4,5)
631 * C) A key=>value associative array
633 * $x = DB_DataObject::factory('mytable');
634 * $x->whereAdd('something = 1')
635 * $ar = $x->fetchAll('id','name');
636 * -- returns array(1=>'fred',2=>'blogs',3=> .......
638 * D) array of objects
639 * $x = DB_DataObject::factory('mytable');
640 * $x->whereAdd('something = 1');
641 * $ar = $x->fetchAll();
643 * E) array of arrays (for example)
644 * $x = DB_DataObject::factory('mytable');
645 * $x->whereAdd('something = 1');
646 * $ar = $x->fetchAll(false,false,'toArray');
649 * @param string|false $k key
650 * @param string|false $v value
651 * @param string|false $method method to call on each result to get array value (eg. 'toArray')
653 * @return array format dependant on arguments, may be empty
655 function fetchAll($k= false, $v = false, $method = false)
657 // should it even do this!!!?!?
659 ( // only do this is we have not been explicit..
660 empty($this->_query['data_select']) ||
661 ($this->_query['data_select'] == '*')
665 $this->selectAdd($k);
667 $this->selectAdd($v);
673 while ($this->fetch()) {
675 $ret[$this->$k] = $this->$v;
678 $ret[] = $k === false ?
679 ($method == false ? clone($this) : $this->$method())
688 * Adds a condition to the WHERE statement, defaults to AND
690 * $object->whereAdd(); //reset or cleaer ewhwer
691 * $object->whereAdd("ID > 20");
692 * $object->whereAdd("age > 20","OR");
694 * @param string $cond condition
695 * @param string $logic optional logic "OR" (defaults to "AND")
697 * @return string|PEAR::Error - previous condition or Error when invalid args found
699 function whereAdd($cond = false, $logic = 'AND')
701 // for PHP5.2.3 - there is a bug with setting array properties of an object.
702 $_query = $this->_query;
704 if (!isset($this->_query) || ($_query === false)) {
705 return $this->raiseError(
706 "You cannot do two queries on the same object (clone it before finding)",
707 DB_DATAOBJECT_ERROR_INVALIDARGS);
710 if ($cond === false) {
711 $r = $this->_query['condition'];
712 $_query['condition'] = '';
713 $this->_query = $_query;
714 return preg_replace('/^\s+WHERE\s+/','',$r);
716 // check input...= 0 or ' ' == error!
718 return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
720 $r = $_query['condition'];
721 if ($_query['condition']) {
722 $_query['condition'] .= " {$logic} ( {$cond} )";
723 $this->_query = $_query;
726 $_query['condition'] = " WHERE ( {$cond} ) ";
727 $this->_query = $_query;
732 * Adds a 'IN' condition to the WHERE statement
734 * $object->whereAddIn('id', $array, 'int'); //minimal usage
735 * $object->whereAddIn('price', $array, 'float', 'OR'); // cast to float, and call whereAdd with 'OR'
736 * $object->whereAddIn('name', $array, 'string'); // quote strings
738 * @param string $key key column to match
739 * @param array $list list of values to match
740 * @param string $type string|int|integer|float|bool cast to type.
741 * @param string $logic optional logic to call whereAdd with eg. "OR" (defaults to "AND")
743 * @return string|PEAR::Error - previous condition or Error when invalid args found
745 function whereAddIn($key, $list, $type, $logic = 'AND')
748 if ($key[0] == '!') {
750 $key = substr($key, 1);
752 // fix type for short entry.
753 $type = $type == 'int' ? 'integer' : $type;
755 if ($type == 'string') {
760 foreach($list as $k) {
762 $ar[] = $type =='string' ? $this->_quote($k) : $k;
765 return $not ? $this->_query['condition'] : $this->whereAdd("1=0");
767 return $this->whereAdd("$key $not IN (". implode(',', $ar). ')', $logic );
773 * Adds a order by condition
775 * $object->orderBy(); //clears order by
776 * $object->orderBy("ID");
777 * $object->orderBy("ID,age");
779 * @param string $order Order
781 * @return none|PEAR::Error - invalid args only
783 function orderBy($order = false)
785 if ($this->_query === false) {
787 "You cannot do two queries on the same object (copy it before finding)",
788 DB_DATAOBJECT_ERROR_INVALIDARGS);
791 if ($order === false) {
792 $this->_query['order_by'] = '';
795 // check input...= 0 or ' ' == error!
797 return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
800 if (!$this->_query['order_by']) {
801 $this->_query['order_by'] = " ORDER BY {$order} ";
804 $this->_query['order_by'] .= " , {$order}";
808 * Adds a group by condition
810 * $object->groupBy(); //reset the grouping
811 * $object->groupBy("ID DESC");
812 * $object->groupBy("ID,age");
814 * @param string $group Grouping
816 * @return none|PEAR::Error - invalid args only
818 function groupBy($group = false)
820 if ($this->_query === false) {
822 "You cannot do two queries on the same object (copy it before finding)",
823 DB_DATAOBJECT_ERROR_INVALIDARGS);
826 if ($group === false) {
827 $this->_query['group_by'] = '';
830 // check input...= 0 or ' ' == error!
832 return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
836 if (!$this->_query['group_by']) {
837 $this->_query['group_by'] = " GROUP BY {$group} ";
840 $this->_query['group_by'] .= " , {$group}";
844 * Adds a having clause
846 * $object->having(); //reset the grouping
847 * $object->having("sum(value) > 0 ");
849 * @param string $having condition
851 * @return none|PEAR::Error - invalid args only
853 function having($having = false)
855 if ($this->_query === false) {
857 "You cannot do two queries on the same object (copy it before finding)",
858 DB_DATAOBJECT_ERROR_INVALIDARGS);
861 if ($having === false) {
862 $this->_query['having'] = '';
865 // check input...= 0 or ' ' == error!
866 if (!trim($having)) {
867 return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
871 if (!$this->_query['having']) {
872 $this->_query['having'] = " HAVING {$having} ";
875 $this->_query['having'] .= " AND {$having}";
881 * $boject->limit(); // clear limit
882 * $object->limit(12);
883 * $object->limit(12,10);
885 * Note this will emit an error on databases other than mysql/postgress
886 * as there is no 'clean way' to implement it. - you should consider refering to
887 * your database manual to decide how you want to implement it.
889 * @param string $a limit start (or number), or blank to reset
890 * @param string $b number
892 * @return none|PEAR::Error - invalid args only
894 function limit($a = null, $b = null)
896 if ($this->_query === false) {
898 "You cannot do two queries on the same object (copy it before finding)",
899 DB_DATAOBJECT_ERROR_INVALIDARGS);
904 $this->_query['limit_start'] = '';
905 $this->_query['limit_count'] = '';
908 // check input...= 0 or ' ' == error!
909 if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
910 || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
911 return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
913 global $_DB_DATAOBJECT;
915 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
917 $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
918 $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
923 * Adds a select columns
925 * $object->selectAdd(); // resets select to nothing!
926 * $object->selectAdd("*"); // default select
927 * $object->selectAdd("unixtime(DATE) as udate");
928 * $object->selectAdd("DATE");
930 * to prepend distict:
931 * $object->selectAdd('distinct ' . $object->selectAdd());
935 * @return mixed null or old string if you reset it.
937 function selectAdd($k = null)
939 if ($this->_query === false) {
941 "You cannot do two queries on the same object (copy it before finding)",
942 DB_DATAOBJECT_ERROR_INVALIDARGS);
946 $old = $this->_query['data_select'];
947 $this->_query['data_select'] = '';
951 // check input...= 0 or ' ' == error!
953 return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
956 if ($this->_query['data_select']) {
957 $this->_query['data_select'] .= ', ';
959 $this->_query['data_select'] .= " $k ";
962 * Adds multiple Columns or objects to select with formating.
964 * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
965 * // note with null it will also clear the '*' default select
966 * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
967 * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
968 * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
969 * objectTableName.colnameA as prefix_colnameA
971 * @param array|object|null the array or object to take column names from.
972 * @param string format in sprintf format (use %s for the colname)
973 * @param string table name eg. if you have joinAdd'd or send $from as an array.
977 function selectAs($from = null,$format = '%s',$tableName=false)
979 global $_DB_DATAOBJECT;
981 if ($this->_query === false) {
983 "You cannot do two queries on the same object (copy it before finding)",
984 DB_DATAOBJECT_ERROR_INVALIDARGS);
988 if ($from === null) {
995 $table = $this->__table;
996 if (is_object($from)) {
997 $table = $from->__table;
998 $from = array_keys($from->table());
1001 if ($tableName !== false) {
1002 $table = $tableName;
1005 if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
1007 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1008 $s = $DB->quoteIdentifier($s);
1009 $format = $DB->quoteIdentifier($format);
1011 foreach ($from as $k) {
1012 $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
1014 $this->_query['data_select'] .= "\n";
1017 * Insert the current objects variables into the database
1019 * Returns the ID of the inserted element (if auto increment or sequences are used.)
1023 * Designed to be extended
1025 * $object = new mytable();
1026 * $object->name = "fred";
1027 * echo $object->insert();
1030 * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
1034 global $_DB_DATAOBJECT;
1036 // we need to write to the connection (For nextid) - so us the real
1037 // one not, a copyied on (as ret-by-ref fails with overload!)
1039 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
1043 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1045 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1047 $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
1048 $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
1051 $this->raiseError("insert:No table definition for {$this->__table}",
1052 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1055 $options = &$_DB_DATAOBJECT['CONFIG'];
1062 $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]) ?
1063 $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] :
1064 $this->sequenceKey();
1066 $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
1067 $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
1068 $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
1070 $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
1073 // nativeSequences or Sequences..
1075 // big check for using sequences
1077 if (($key !== false) && !$useNative) {
1080 $keyvalue = $DB->nextId($this->__table);
1082 $f = $DB->getOption('seqname_format');
1083 $DB->setOption('seqname_format','%s');
1084 $keyvalue = $DB->nextId($seq);
1085 $DB->setOption('seqname_format',$f);
1087 if (PEAR::isError($keyvalue)) {
1088 $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1091 $this->$key = $keyvalue;
1094 // if we haven't set disable_null_strings to "full"
1095 $ignore_null = !isset($options['disable_null_strings'])
1096 || !is_string($options['disable_null_strings'])
1097 || strtolower($options['disable_null_strings']) !== 'full' ;
1100 foreach($items as $k => $v) {
1102 // if we are using autoincrement - skip the column...
1103 if ($key && ($k == $key) && $useNative) {
1110 // Ignore variables which aren't set to a value
1111 if ( !isset($this->$k) && $ignore_null) {
1114 // dont insert data into mysql timestamps
1115 // use query() if you really want to do this!!!!
1116 if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1125 $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
1127 if (is_a($this->$k,'DB_DataObject_Cast')) {
1128 $value = $this->$k->toString($v,$DB);
1129 if (PEAR::isError($value)) {
1130 $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
1138 if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
1139 $rightq .= " NULL ";
1142 // DATE is empty... on a col. that can be null..
1143 // note: this may be usefull for time as well..
1145 (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
1146 !($v & DB_DATAOBJECT_NOTNULL)) {
1148 $rightq .= " NULL ";
1153 if ($v & DB_DATAOBJECT_STR) {
1154 $rightq .= $this->_quote((string) (
1155 ($v & DB_DATAOBJECT_BOOL) ?
1156 // this is thanks to the braindead idea of postgres to
1157 // use t/f for boolean.
1158 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
1163 if (is_numeric($this->$k)) {
1164 $rightq .=" {$this->$k} ";
1167 /* flag up string values - only at debug level... !!!??? */
1168 if (is_object($this->$k) || is_array($this->$k)) {
1169 $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k,true),'ERROR');
1172 // at present we only cast to integers
1173 // - V2 may store additional data about float/int
1174 $rightq .= ' ' . intval($this->$k) . ' ';
1178 // not sure why we let empty insert here.. - I guess to generate a blank row..
1181 if ($leftq || $useNative) {
1182 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1185 if (($dbtype == 'pgsql') && empty($leftq)) {
1186 $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
1188 $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
1194 if (PEAR::isError($r)) {
1195 $this->raiseError($r);
1204 // now do we have an integer key!
1206 if ($key && $useNative) {
1210 $method = "{$dbtype}_insert_id";
1211 $this->$key = $method(
1212 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
1217 // note this is not really thread safe - you should wrapp it with
1218 // transactions = eg.
1219 // $db->query('BEGIN');
1221 // $db->query('COMMIT');
1222 $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1223 $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
1224 $mssql_key = $DB->$method("SELECT @@IDENTITY");
1225 if (PEAR::isError($mssql_key)) {
1226 $this->raiseError($mssql_key);
1229 $this->$key = $mssql_key;
1234 $seq = $DB->getSequenceName(strtolower($this->__table));
1236 $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1237 $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
1238 $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
1241 if (PEAR::isError($pgsql_key)) {
1242 $this->raiseError($pgsql_key);
1245 $this->$key = $pgsql_key;
1249 $this->$key = array_shift (
1252 "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
1253 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
1265 if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
1266 $this->_clear_cache();
1273 $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1278 * Updates current objects variables into the database
1279 * uses the keys() to decide how to update
1280 * Returns the true on success
1284 * $object = DB_DataObject::factory('mytable');
1285 * $object->get("ID",234);
1286 * $object->email="testing@test.com";
1287 * if(!$object->update())
1288 * echo "UPDATE FAILED";
1290 * to only update changed items :
1291 * $dataobject->get(132);
1292 * $original = $dataobject; // clone/copy it..
1293 * $dataobject->setFrom($_POST);
1294 * if ($dataobject->validate()) {
1295 * $dataobject->update($original);
1296 * } // otherwise an error...
1298 * performing global updates:
1299 * $object = DB_DataObject::factory('mytable');
1300 * $object->status = "dead";
1301 * $object->whereAdd('age > 150');
1302 * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
1304 * @param object dataobject (optional) | DB_DATAOBJECT_WHEREADD_ONLY - used to only update changed items.
1306 * @return int rows affected or false on failure
1308 function update($dataObject = false)
1310 global $_DB_DATAOBJECT;
1311 // connect will load the config!
1315 $original_query = $this->_query;
1317 $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
1318 $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
1320 // only apply update against sequence key if it is set?????
1322 $seq = $this->sequenceKey();
1323 if ($seq[0] !== false) {
1324 $keys = array($seq[0]);
1325 if (!isset($this->{$keys[0]}) && $dataObject !== true) {
1326 $this->raiseError("update: trying to perform an update without
1327 the key set, and argument to update is not
1328 DB_DATAOBJECT_WHEREADD_ONLY
1329 ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1333 $keys = $this->keys();
1338 $this->raiseError("update:No table definition for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1345 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1346 $dbtype = $DB->dsn["phptype"];
1347 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1348 $options = $_DB_DATAOBJECT['CONFIG'];
1351 $ignore_null = !isset($options['disable_null_strings'])
1352 || !is_string($options['disable_null_strings'])
1353 || strtolower($options['disable_null_strings']) !== 'full' ;
1356 foreach($items as $k => $v) {
1358 if (!isset($this->$k) && $ignore_null) {
1361 // ignore stuff thats
1363 // dont write things that havent changed..
1364 if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
1368 // - dont write keys to left.!!!
1369 if (in_array($k,$keys)) {
1373 // dont insert data into mysql timestamps
1374 // use query() if you really want to do this!!!!
1375 if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1384 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
1386 if (is_a($this->$k,'DB_DataObject_Cast')) {
1387 $value = $this->$k->toString($v,$DB);
1388 if (PEAR::isError($value)) {
1389 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
1392 $settings .= "$kSql = $value ";
1396 // special values ... at least null is handled...
1397 if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
1398 $settings .= "$kSql = NULL ";
1401 // DATE is empty... on a col. that can be null..
1402 // note: this may be usefull for time as well..
1404 (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
1405 !($v & DB_DATAOBJECT_NOTNULL)) {
1407 $settings .= "$kSql = NULL ";
1412 if ($v & DB_DATAOBJECT_STR) {
1413 $settings .= "$kSql = ". $this->_quote((string) (
1414 ($v & DB_DATAOBJECT_BOOL) ?
1415 // this is thanks to the braindead idea of postgres to
1416 // use t/f for boolean.
1417 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
1422 if (is_numeric($this->$k)) {
1423 $settings .= "$kSql = {$this->$k} ";
1426 // at present we only cast to integers
1427 // - V2 may store additional data about float/int
1428 $settings .= "$kSql = " . intval($this->$k) . ' ';
1432 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1433 $this->debug("got keys as ".serialize($keys),3);
1435 if ($dataObject !== true) {
1436 $this->_build_condition($items,$keys);
1438 // prevent wiping out of data!
1439 if (empty($this->_query['condition'])) {
1440 $this->raiseError("update: global table update not available
1441 do \$do->whereAdd('1=1'); if you really want to do that.
1442 ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1449 // echo " $settings, $this->condition ";
1450 if ($settings && isset($this->_query) && $this->_query['condition']) {
1452 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1454 $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
1456 // restore original query conditions.
1457 $this->_query = $original_query;
1459 if (PEAR::isError($r)) {
1460 $this->raiseError($r);
1467 $this->_clear_cache();
1470 // restore original query conditions.
1471 $this->_query = $original_query;
1473 // if you manually specified a dataobject, and there where no changes - then it's ok..
1474 if ($dataObject !== false) {
1479 "update: No Data specifed for query $settings , {$this->_query['condition']}",
1480 DB_DATAOBJECT_ERROR_NODATA);
1485 * Deletes items from table which match current objects variables
1487 * Returns the true on success
1491 * Designed to be extended
1493 * $object = new mytable();
1495 * echo $object->delete(); // builds a conditon
1497 * $object = new mytable();
1498 * $object->whereAdd('age > 12');
1499 * $object->limit(1);
1500 * $object->orderBy('age DESC');
1501 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
1503 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1504 * we will build the condition only using the whereAdd's. Default is to
1505 * build the condition only using the object parameters.
1508 * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
1510 function delete($useWhere = false)
1512 global $_DB_DATAOBJECT;
1513 // connect will load the config!
1515 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1516 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1518 $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
1522 $keys = $this->keys();
1523 $this->_query = array(); // as it's probably unset!
1524 $this->_query['condition'] = ''; // default behaviour not to use where condition
1525 $this->_build_condition($this->table(),$keys);
1526 // if primary keys are not set then use data from rest of object.
1527 if (!$this->_query['condition']) {
1528 $this->_build_condition($this->table(),array(),$keys);
1534 // don't delete without a condition
1535 if (($this->_query !== false) && $this->_query['condition']) {
1537 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1539 // using a joined delete. - with useWhere..
1540 $sql .= (!empty($this->_join) && $useWhere) ?
1541 "{$table} FROM {$table} {$this->_join} " :
1544 $sql .= $this->_query['condition']. $extra_cond;
1548 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
1550 if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
1551 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
1553 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
1557 $DB->setLimit( $this->_query['limit_count'],$this->_query['limit_start']);
1563 $r = $this->_query($sql);
1566 if (PEAR::isError($r)) {
1567 $this->raiseError($r);
1573 $this->_clear_cache();
1576 $this->raiseError("delete: No condition specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1582 * fetches a specific row into this object variables
1584 * Not recommended - better to use fetch()
1586 * Returens true on success
1588 * @param int $row row
1590 * @return boolean true on success
1592 function fetchRow($row = null)
1594 global $_DB_DATAOBJECT;
1595 if (empty($_DB_DATAOBJECT['CONFIG'])) {
1596 $this->_loadConfig();
1598 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1599 $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
1601 if (!$this->__table) {
1602 $this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1605 if ($row === null) {
1606 $this->raiseError("fetchrow: No row specified", DB_DATAOBJECT_ERROR_INVALIDARGS);
1610 $this->raiseError("fetchrow: No results avaiable", DB_DATAOBJECT_ERROR_NODATA);
1613 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1614 $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
1618 $result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
1619 $array = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC,$row);
1620 if (!is_array($array)) {
1621 $this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
1625 foreach($array as $k => $v) {
1626 $kk = str_replace(".", "_", $k);
1627 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1628 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
1630 $this->$kk = $array[$k];
1633 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1634 $this->debug("{$this->__table} DONE", "fetchrow", 3);
1640 * Find the number of results from a simple query
1644 * $object = new mytable();
1645 * $object->name = "fred";
1646 * echo $object->count();
1647 * echo $object->count(true); // dont use object vars.
1648 * echo $object->count('distinct mycol'); count distinct mycol.
1649 * echo $object->count('distinct mycol',true); // dont use object vars.
1650 * echo $object->count('distinct'); // count distinct id (eg. the primary key)
1653 * @param bool|string (optional)
1654 * (true|false => see below not on whereAddonly)
1656 * "DISTINCT" => does a distinct count on the tables 'key' column
1657 * otherwise => normally it counts primary keys - you can use
1658 * this to do things like $do->count('distinct mycol');
1660 * @param bool $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1661 * we will build the condition only using the whereAdd's. Default is to
1662 * build the condition using the object parameters as well.
1667 function count($countWhat = false,$whereAddOnly = false)
1669 global $_DB_DATAOBJECT;
1671 if (is_bool($countWhat)) {
1672 $whereAddOnly = $countWhat;
1676 $items = $t->table();
1678 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1681 if (!isset($t->_query)) {
1683 "You cannot do run count after you have run fetch()",
1684 DB_DATAOBJECT_ERROR_INVALIDARGS);
1688 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1691 if (!$whereAddOnly && $items) {
1692 $t->_build_condition($items);
1694 $keys = $this->keys();
1696 if (empty($keys[0]) && (!is_string($countWhat) || (strtoupper($countWhat) == 'DISTINCT'))) {
1698 "You cannot do run count without keys - use \$do->count('id'), or use \$do->count('distinct id')';",
1699 DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
1703 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1704 $key_col = empty($keys[0]) ? '' : (($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]));
1705 $as = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
1707 // support distinct on default keys.
1708 $countWhat = (strtoupper($countWhat) == 'DISTINCT') ?
1709 "DISTINCT {$table}.{$key_col}" : $countWhat;
1711 $countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
1714 "SELECT count({$countWhat}) as $as
1715 FROM $table {$t->_join} {$t->_query['condition']}");
1716 if (PEAR::isError($r)) {
1720 $result = &$_DB_DATAOBJECT['RESULTS'][$t->_DB_resultid];
1721 $l = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ORDERED);
1722 // free the results - essential on oracle.
1729 * sends raw query to database
1731 * Since _query has to be a private 'non overwriteable method', this is a relay
1733 * @param string $string SQL Query
1735 * @return void or DB_Error
1737 function query($string)
1739 return $this->_query($string);
1744 * an escape wrapper around DB->escapeSimple()
1745 * can be used when adding manual queries or clauses
1747 * $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
1749 * @param string $string value to be escaped
1750 * @param bool $likeEscape escapes % and _ as well. - so like queries can be protected.
1754 function escape($string, $likeEscape=false)
1756 global $_DB_DATAOBJECT;
1758 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1759 // mdb2 uses escape...
1760 $dd = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
1761 $ret = ($dd == 'DB') ? $DB->escapeSimple($string) : $DB->escape($string);
1763 $ret = str_replace(array('_','%'), array('\_','\%'), $ret);
1769 /* ==================================================== */
1770 /* Major Private Vars */
1771 /* ==================================================== */
1774 * The Database connection dsn (as described in the PEAR DB)
1775 * only used really if you are writing a very simple application/test..
1776 * try not to use this - it is better stored in configuration files..
1781 var $_database_dsn = '';
1784 * The Database connection id (md5 sum of databasedsn)
1789 var $_database_dsn_md5 = '';
1793 * created in __connection
1798 var $_database = '';
1804 * This replaces alot of the private variables
1805 * used to build a query, it is unset after find() is run.
1812 var $_query = array(
1813 'condition' => '', // the WHERE condition
1814 'group_by' => '', // the GROUP BY condition
1815 'order_by' => '', // the ORDER BY condition
1816 'having' => '', // the HAVING condition
1817 'limit_start' => '', // the LIMIT condition
1818 'limit_count' => '', // the LIMIT condition
1819 'data_select' => '*', // the columns to be SELECTed
1820 'unions' => array(), // the added unions
1827 * Database result id (references global $_DB_DataObject[results]
1835 * ResultFields - on the last call to fetch(), resultfields is sent here,
1836 * so we can clean up the memory.
1841 var $_resultFields = false;
1844 /* ============================================================== */
1845 /* Table definition layer (started of very private but 'came out'*/
1846 /* ============================================================== */
1849 * Autoload or manually load the table definitions
1853 * DB_DataObject::databaseStructure( 'databasename',
1854 * parse_ini_file('mydb.ini',true),
1855 * parse_ini_file('mydb.link.ini',true));
1857 * obviously you dont have to use ini files.. (just return array similar to ini files..)
1859 * It should append to the table structure array
1862 * @param optional string name of database to assign / read
1863 * @param optional array structure of database, and keys
1864 * @param optional array table links
1867 * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
1868 * or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
1870 function databaseStructure()
1873 global $_DB_DATAOBJECT;
1877 if ($args = func_get_args()) {
1879 if (count($args) == 1) {
1881 // this returns all the tables and their structure..
1882 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1883 $this->debug("Loading Generator as databaseStructure called with args",1);
1886 $x = new DB_DataObject;
1887 $x->_database = $args[0];
1889 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1891 $tables = $DB->getListOf('tables');
1892 class_exists('DB_DataObject_Generator') ? '' :
1893 require_once 'DB/DataObject/Generator.php';
1895 foreach($tables as $table) {
1896 $y = new DB_DataObject_Generator;
1897 $y->fillTableSchema($x->_database,$table);
1899 return $_DB_DATAOBJECT['INI'][$x->_database];
1902 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
1903 $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
1905 if (isset($args[1])) {
1906 $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
1907 $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
1916 if (!$this->_database) {
1921 if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
1923 // database loaded - but this is table is not available..
1925 empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])
1926 && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
1928 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1929 $this->debug("Loading Generator to fetch Schema",1);
1931 class_exists('DB_DataObject_Generator') ? '' :
1932 require_once 'DB/DataObject/Generator.php';
1935 $x = new DB_DataObject_Generator;
1936 $x->fillTableSchema($this->_database,$this->__table);
1942 if (empty($_DB_DATAOBJECT['CONFIG'])) {
1943 DB_DataObject::_loadConfig();
1946 // if you supply this with arguments, then it will take those
1947 // as the database and links array...
1949 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
1950 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
1953 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
1954 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
1955 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
1956 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
1960 $_DB_DATAOBJECT['INI'][$this->_database] = array();
1961 foreach ($schemas as $ini) {
1962 if (file_exists($ini) && is_file($ini)) {
1964 $_DB_DATAOBJECT['INI'][$this->_database] = array_merge(
1965 $_DB_DATAOBJECT['INI'][$this->_database],
1966 parse_ini_file($ini, true)
1969 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1970 if (!is_readable ($ini)) {
1971 $this->debug("ini file is not readable: $ini","databaseStructure",1);
1973 $this->debug("Loaded ini file: $ini","databaseStructure",1);
1977 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1978 $this->debug("Missing ini file: $ini","databaseStructure",1);
1983 // now have we loaded the structure..
1985 if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
1988 // - if not try building it..
1989 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
1990 class_exists('DB_DataObject_Generator') ? '' :
1991 require_once 'DB/DataObject/Generator.php';
1993 $x = new DB_DataObject_Generator;
1994 $x->fillTableSchema($this->_database,$this->__table);
1995 // should this fail!!!???
1998 $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
1999 "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
2000 // we have to die here!! - it causes chaos if we dont (including looping forever!)
2001 $this->raiseError( "Unable to load schema for database and table (turn debugging up to 5 for full error message)", DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
2011 * Return or assign the name of the current table
2014 * @param string optinal table name to set
2016 * @return string The name of the current table
2018 function tableName()
2020 $args = func_get_args();
2022 $this->__table = $args[0];
2024 return $this->__table;
2028 * Return or assign the name of the current database
2030 * @param string optional database name to set
2032 * @return string The name of the current database
2036 $args = func_get_args();
2038 $this->_database = $args[0];
2040 return $this->_database;
2044 * get/set an associative array of table columns
2047 * @param array key=>type array
2048 * @return array (associative)
2053 // for temporary storage of database fields..
2054 // note this is not declared as we dont want to bloat the print_r output
2055 $args = func_get_args();
2057 $this->_database_fields = $args[0];
2059 if (isset($this->_database_fields)) {
2060 return $this->_database_fields;
2064 global $_DB_DATAOBJECT;
2065 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2069 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
2070 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
2073 $this->databaseStructure();
2077 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
2078 $ret = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
2085 * get/set an array of table primary keys
2087 * set usage: $do->keys('id','code');
2089 * This is defined in the table definition if it gets it wrong,
2090 * or you do not want to use ini tables, you can override this.
2091 * @param string optional set the key
2092 * @param * optional set more keys
2098 // for temporary storage of database fields..
2099 // note this is not declared as we dont want to bloat the print_r output
2100 $args = func_get_args();
2102 $this->_database_keys = $args;
2104 if (isset($this->_database_keys)) {
2105 return $this->_database_keys;
2108 global $_DB_DATAOBJECT;
2109 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2112 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
2113 return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
2115 $this->databaseStructure();
2117 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
2118 return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
2123 * get/set an sequence key
2125 * by default it returns the first key from keys()
2126 * set usage: $do->sequenceKey('id',true);
2128 * override this to return array(false,false) if table has no real sequence key.
2130 * @param string optional the key sequence/autoinc. key
2131 * @param boolean optional use native increment. default false
2132 * @param false|string optional native sequence name
2134 * @return array (column,use_native,sequence_name)
2136 function sequenceKey()
2138 global $_DB_DATAOBJECT;
2141 if (!$this->_database) {
2145 if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
2146 $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
2150 $args = func_get_args();
2152 $args[1] = isset($args[1]) ? $args[1] : false;
2153 $args[2] = isset($args[2]) ? $args[2] : false;
2154 $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = $args;
2156 if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table])) {
2157 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table];
2159 // end call setting (eg. $do->sequenceKeys(a,b,c); )
2164 $keys = $this->keys();
2166 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]
2167 = array(false,false,false);
2171 $table = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
2172 $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
2174 $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
2182 if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table])) {
2183 $seqname = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table];
2184 if (strpos($seqname,':') !== false) {
2185 list($usekey,$seqname) = explode(':',$seqname);
2190 // if the key is not an integer - then it's not a sequence or native
2191 if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
2192 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,false);
2196 if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
2197 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
2198 if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
2199 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2201 if (is_string($ignore)) {
2202 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
2204 if (in_array($this->__table,$ignore)) {
2205 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2210 $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
2212 // if you are using an old ini file - go back to old behaviour...
2213 if (is_numeric($realkeys[$usekey])) {
2214 $realkeys[$usekey] = 'N';
2217 // multiple unique primary keys without a native sequence...
2218 if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
2219 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2221 // use native sequence keys...
2222 // technically postgres native here...
2223 // we need to get the new improved tabledata sorted out first.
2225 if ( in_array($dbtype , array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
2226 ($table[$usekey] & DB_DATAOBJECT_INT) &&
2227 isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
2229 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,true,$seqname);
2231 // if not a native autoinc, and we have not assumed all primary keys are sequence
2232 if (($realkeys[$usekey] != 'N') &&
2233 !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
2234 return array(false,false,false);
2236 // I assume it's going to try and be a nextval DB sequence.. (not native)
2237 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,false,$seqname);
2242 /* =========================================================== */
2243 /* Major Private Methods - the core part! */
2244 /* =========================================================== */
2249 * clear the cache values for this class - normally done on insert/update etc.
2254 function _clear_cache()
2256 global $_DB_DATAOBJECT;
2258 $class = strtolower(get_class($this));
2260 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2261 $this->debug("Clearing Cache for ".$class,1);
2264 if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
2265 unset($_DB_DATAOBJECT['CACHE'][$class]);
2271 * backend wrapper for quoting, as MDB2 and DB do it differently...
2274 * @return string quoted
2277 function _quote($str)
2279 global $_DB_DATAOBJECT;
2280 return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
2281 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
2282 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
2283 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
2288 * connects to the database
2291 * TODO: tidy this up - This has grown to support a number of connection options like
2292 * a) dynamic changing of ini file to change which database to connect to
2293 * b) multi data via the table_{$table} = dsn ini option
2294 * c) session based storage.
2297 * @return true | PEAR::error
2301 global $_DB_DATAOBJECT;
2302 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2303 $this->_loadConfig();
2305 // Set database driver for reference
2306 $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
2307 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
2309 // is it already connected ?
2310 if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2312 // connection is an error...
2313 if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2314 return $this->raiseError(
2315 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
2316 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2321 if (empty($this->_database)) {
2322 $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2323 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2325 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2326 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2327 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2331 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2332 && is_file($this->_database)) {
2333 $this->_database = basename($this->_database);
2335 if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase') {
2336 $this->_database = substr(basename($this->_database), 0, -4);
2340 // theoretically we have a md5, it's listed in connections and it's not an error.
2341 // so everything is ok!
2346 // it's not currently connected!
2347 // try and work out what to use for the dsn !
2349 $options= &$_DB_DATAOBJECT['CONFIG'];
2350 // if the databse dsn dis defined in the object..
2351 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
2354 if (!$this->_database) {
2355 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
2357 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2358 $this->debug("Checking for database specific ini ('{$this->_database}') : database_{$this->_database} in options","CONNECT");
2361 if ($this->_database && !empty($options["database_{$this->_database}"])) {
2362 $dsn = $options["database_{$this->_database}"];
2363 } else if (!empty($options['database'])) {
2364 $dsn = $options['database'];
2369 // if still no database...
2371 return $this->raiseError(
2372 "No database name / dsn found anywhere",
2373 DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
2379 if (is_string($dsn)) {
2380 $this->_database_dsn_md5 = md5($dsn);
2382 /// support array based dsn's
2383 $this->_database_dsn_md5 = md5(serialize($dsn));
2386 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2387 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2388 $this->debug("USING CACHED CONNECTION", "CONNECT",3);
2393 if (!$this->_database) {
2395 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2396 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2397 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2398 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2400 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2401 && is_file($this->_database))
2403 $this->_database = basename($this->_database);
2408 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2409 $this->debug("NEW CONNECTION TP DATABASE :" .$this->_database , "CONNECT",3);
2410 /* actualy make a connection */
2411 $this->debug(print_r($dsn,true) ." {$this->_database_dsn_md5}", "CONNECT",3);
2414 // Note this is verbose deliberatly!
2416 if ($db_driver == 'DB') {
2418 /* PEAR DB connect */
2420 // this allows the setings of compatibility on DB
2421 $db_options = PEAR::getStaticProperty('DB','options');
2422 require_once 'DB.php';
2424 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &DB::connect($dsn,$db_options);
2426 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &DB::connect($dsn);
2430 /* assumption is MDB2 */
2431 require_once 'MDB2.php';
2432 // this allows the setings of compatibility on MDB2
2433 $db_options = PEAR::getStaticProperty('MDB2','options');
2434 $db_options = is_array($db_options) ? $db_options : array();
2435 $db_options['portability'] = isset($db_options['portability'] )
2436 ? $db_options['portability'] : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
2437 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &MDB2::connect($dsn,$db_options);
2442 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2443 $this->debug(serialize($_DB_DATAOBJECT['CONNECTIONS']), "CONNECT",5);
2445 if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2446 $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED",5);
2447 return $this->raiseError(
2448 "Connect failed, turn on debugging to 5 see why",
2449 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2454 if (empty($this->_database)) {
2455 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2457 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2458 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2459 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2462 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2463 && is_file($this->_database))
2465 $this->_database = basename($this->_database);
2469 // Oracle need to optimize for portibility - not sure exactly what this does though :)
2470 $c = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2476 * sends query to database - this is the private one that must work
2477 * - internal functions use this rather than $this->query()
2479 * @param string $string
2481 * @return mixed none or PEAR_Error
2483 function _query($string)
2485 global $_DB_DATAOBJECT;
2489 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2491 $options = &$_DB_DATAOBJECT['CONFIG'];
2493 $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
2494 'DB': $_DB_DATAOBJECT['CONFIG']['db_driver'];
2496 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2497 $this->debug($string,$log="QUERY");
2501 if (strtoupper($string) == 'BEGIN') {
2502 if ($_DB_driver == 'DB') {
2503 $DB->autoCommit(false);
2505 $DB->beginTransaction();
2507 // db backend adds begin anyway from now on..
2510 if (strtoupper($string) == 'COMMIT') {
2511 $res = $DB->commit();
2512 if ($_DB_driver == 'DB') {
2513 $DB->autoCommit(true);
2518 if (strtoupper($string) == 'ROLLBACK') {
2520 if ($_DB_driver == 'DB') {
2521 $DB->autoCommit(true);
2527 if (!empty($options['debug_ignore_updates']) &&
2528 (strtolower(substr(trim($string), 0, 6)) != 'select') &&
2529 (strtolower(substr(trim($string), 0, 4)) != 'show') &&
2530 (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
2532 $this->debug('Disabling Update as you are in debug mode');
2533 return $this->raiseError("Disabling Update as you are in debug mode", null) ;
2536 //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
2537 // this will only work when PEAR:DB supports it.
2538 //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
2542 $t= explode(' ',microtime());
2543 $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
2546 for ($tries = 0;$tries < 3;$tries++) {
2548 if ($_DB_driver == 'DB') {
2550 $result = $DB->query($string);
2552 switch (strtolower(substr(trim($string),0,6))) {
2557 $result = $DB->exec($string);
2561 $result = $DB->query($string);
2566 // see if we got a failure.. - try again a few times..
2567 if (!is_a($result,'PEAR_Error')) {
2570 if ($result->getCode() != -14) { // *DB_ERROR_NODBSELECTED
2571 break; // not a connection error..
2573 sleep(1); // wait before retyring..
2574 $DB->connect($DB->dsn);
2578 if (is_a($result,'PEAR_Error')) {
2579 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2580 $this->debug($result->toString(), "Query Error",1 );
2582 return $this->raiseError($result);
2584 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2585 $t= explode(' ',microtime());
2586 $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
2587 $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query',1);
2589 switch (strtolower(substr(trim($string),0,6))) {
2593 if ($_DB_driver == 'DB') {
2595 return $DB->affectedRows();
2599 if (is_object($result)) {
2600 // lets hope that copying the result object is OK!
2602 $_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
2603 $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
2604 $this->_DB_resultid = $_DB_resultid;
2607 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2608 $this->debug(serialize($result), 'RESULT',5);
2610 if (method_exists($result, 'numrows')) {
2611 if ($_DB_driver == 'DB') {
2612 $DB->expectError(DB_ERROR_UNSUPPORTED);
2614 $DB->expectError(MDB2_ERROR_UNSUPPORTED);
2616 $this->N = $result->numrows();
2617 if (is_a($this->N,'PEAR_Error')) {
2625 * Builds the WHERE based on the values of of this object
2627 * @param mixed $keys
2628 * @param array $filter (used by update to only uses keys in this filter list).
2629 * @param array $negative_filter (used by delete to prevent deleting using the keys mentioned..)
2633 function _build_condition($keys, $filter = array(),$negative_filter=array())
2635 global $_DB_DATAOBJECT;
2637 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2639 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
2640 $options = $_DB_DATAOBJECT['CONFIG'];
2642 // if we dont have query vars.. - reset them.
2643 if ($this->_query === false) {
2644 $x = new DB_DataObject;
2645 $this->_query= $x->_query;
2649 foreach($keys as $k => $v) {
2650 // index keys is an indexed array
2651 /* these filter checks are a bit suspicious..
2652 - need to check that update really wants to work this way */
2655 if (!in_array($k, $filter)) {
2659 if ($negative_filter) {
2660 if (in_array($k, $negative_filter)) {
2664 if (!isset($this->$k)) {
2668 $kSql = $quoteIdentifiers
2669 ? ( $DB->quoteIdentifier($this->__table) . '.' . $DB->quoteIdentifier($k) )
2670 : "{$this->__table}.{$k}";
2674 if (is_a($this->$k,'DB_DataObject_Cast')) {
2675 $dbtype = $DB->dsn["phptype"];
2676 $value = $this->$k->toString($v,$DB);
2677 if (PEAR::isError($value)) {
2678 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
2681 if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2682 $this->whereAdd(" $kSql IS NULL");
2685 $this->whereAdd(" $kSql = $value");
2689 if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
2690 $this->whereAdd(" $kSql IS NULL");
2695 if ($v & DB_DATAOBJECT_STR) {
2696 $this->whereAdd(" $kSql = " . $this->_quote((string) (
2697 ($v & DB_DATAOBJECT_BOOL) ?
2698 // this is thanks to the braindead idea of postgres to
2699 // use t/f for boolean.
2700 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
2705 if (is_numeric($this->$k)) {
2706 $this->whereAdd(" $kSql = {$this->$k}");
2709 /* this is probably an error condition! */
2710 $this->whereAdd(" $kSql = ".intval($this->$k));
2715 * autoload Class relating to a table
2716 * (depreciated - use ::factory)
2718 * @param string $table table
2720 * @return string classname on Success
2722 function staticAutoloadTable($table)
2724 global $_DB_DATAOBJECT;
2725 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2726 DB_DataObject::_loadConfig();
2728 $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2729 $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
2730 $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2732 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2733 $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
2739 * classic factory method for loading a table class
2740 * usage: $do = DB_DataObject::factory('person')
2741 * WARNING - this may emit a include error if the file does not exist..
2742 * use @ to silence it (if you are sure it is acceptable)
2743 * eg. $do = @DB_DataObject::factory('person')
2745 * table name can bedatabasename/table
2746 * - and allow modular dataobjects to be written..
2747 * (this also helps proxy creation)
2749 * Experimental Support for Multi-Database factory eg. mydatabase.mytable
2752 * @param string $table tablename (use blank to create a new instance of the same class.)
2754 * @return DataObject|PEAR_Error
2759 function factory($table = '') {
2760 global $_DB_DATAOBJECT;
2763 // multi-database support.. - experimental.
2766 if (strpos( $table,'/') !== false ) {
2767 list($database,$table) = explode('.',$table, 2);
2771 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2772 DB_DataObject::_loadConfig();
2774 // no configuration available for database
2775 if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_'.$database])) {
2776 return DB_DataObject::raiseError(
2777 "unable to find database_{$database} in Configuration, It is required for factory with database"
2778 , 0, PEAR_ERROR_DIE );
2783 if ($table === '') {
2784 if (is_a($this,'DB_DataObject') && strlen($this->__table)) {
2785 $table = $this->__table;
2787 return DB_DataObject::raiseError(
2788 "factory did not recieve a table name",
2789 DB_DATAOBJECT_ERROR_INVALIDARGS);
2793 // does this need multi db support??
2794 $cp = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2795 explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']['class_prefix']) : '';
2797 // multiprefix support.
2798 $tbl = preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2799 if (is_array($cp)) {
2801 foreach($cp as $cpr) {
2802 $ce = substr(phpversion(),0,1) > 4 ? class_exists($cpr . $tbl,false) : class_exists($cpr . $tbl);
2804 $class = $cpr . $tbl;
2807 $class[] = $cpr . $tbl;
2811 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2815 $rclass = $ce ? $class : DB_DataObject::_autoloadClass($class, $table);
2817 // proxy = full|light
2818 if (!$rclass && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
2820 DB_DataObject::debug("FAILED TO Autoload $database.$table - using proxy.","FACTORY",1);
2823 $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
2824 // if you have loaded (some other way) - dont try and load it again..
2825 class_exists('DB_DataObject_Generator') ? '' :
2826 require_once 'DB/DataObject/Generator.php';
2828 $d = new DB_DataObject;
2830 $d->__table = $table;
2831 if (is_a($ret = $d->_connect(), 'PEAR_Error')) {
2835 $x = new DB_DataObject_Generator;
2836 return $x->$proxyMethod( $d->_database, $table);
2840 return DB_DataObject::raiseError(
2841 "factory could not find class " .
2842 (is_array($class) ? implode(PATH_SEPARATOR, $class) : $class ).
2844 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2847 if (!empty($database)) {
2848 DB_DataObject::debug("Setting database to $database","FACTORY",1);
2849 $ret->database($database);
2856 * @param string|array $class Class
2857 * @param string $table Table trying to load.
2859 * @return string classname on Success
2861 function _autoloadClass($class, $table=false)
2863 global $_DB_DATAOBJECT;
2865 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2866 DB_DataObject::_loadConfig();
2868 $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2869 '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
2871 $table = $table ? $table : substr($class,strlen($class_prefix));
2873 // only include the file if it exists - and barf badly if it has parse errors :)
2874 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
2878 // class_location = mydir/ => maps to mydir/Tablename.php
2879 // class_location = mydir/myfile_%s.php => maps to mydir/myfile_Tablename
2880 // with directory sepr
2881 // class_location = mydir/:mydir2/: => tries all of thes locations.
2882 $cl = $_DB_DATAOBJECT['CONFIG']['class_location'];
2886 case (strpos($cl ,'%s') !== false):
2887 $file = sprintf($cl , preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
2890 case (strpos($cl , PATH_SEPARATOR) !== false):
2892 foreach(explode(PATH_SEPARATOR, $cl ) as $p) {
2893 $file[] = $p .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2897 $file = $cl .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2901 $cls = is_array($class) ? $class : array($class);
2903 if (is_array($file) || !file_exists($file)) {
2906 $file = is_array($file) ? $file : array($file);
2907 $search = implode(PATH_SEPARATOR, $file);
2908 foreach($file as $f) {
2909 foreach(explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
2910 $ff = empty($p) ? $f : "$p/$f";
2912 if (file_exists($ff)) {
2923 DB_DataObject::raiseError(
2924 "autoload:Could not find class " . implode(',', $cls) .
2925 " using class_location value :" . $search .
2926 " using include_path value :" . ini_get('include_path'),
2927 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2936 foreach($cls as $c) {
2937 $ce = substr(phpversion(),0,1) > 4 ? class_exists($c,false) : class_exists($c);
2944 DB_DataObject::raiseError(
2945 "autoload:Could not autoload " . implode(',', $cls) ,
2946 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2955 * Have the links been loaded?
2956 * if they have it contains a array of those variables.
2959 * @var boolean | array
2961 var $_link_loaded = false;
2964 * Get the links associate array as defined by the links.ini file.
2968 * Should look a bit like
2969 * [local_col_name] => "related_tablename:related_col_name"
2972 * @return array|null
2973 * array = if there are links defined for this table.
2974 * empty array - if there is a links.ini file, but no links on this table
2975 * null - if no links.ini exists for this database (hence try auto_links).
2977 * @see DB_DataObject::getLinks(), DB_DataObject::getLink()
2982 global $_DB_DATAOBJECT;
2983 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2984 $this->_loadConfig();
2986 // have to connect.. -> otherwise things break later.
2989 if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
2990 return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
2997 // attempt to load links file here..
2999 if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
3000 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
3001 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
3004 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
3005 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
3006 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
3007 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
3011 $_DB_DATAOBJECT['LINKS'][$this->_database] = array();
3012 foreach ($schemas as $ini) {
3015 isset($_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"]) ?
3016 $_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"] :
3017 str_replace('.ini','.links.ini',$ini);
3019 if (file_exists($links) && is_file($links)) {
3020 /* not sure why $links = ... here - TODO check if that works */
3021 $_DB_DATAOBJECT['LINKS'][$this->_database] = array_merge(
3022 $_DB_DATAOBJECT['LINKS'][$this->_database],
3023 parse_ini_file($links, true)
3026 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
3027 $this->debug("Loaded links.ini file: $links","links",1);
3030 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
3031 $this->debug("Missing links.ini file: $links","links",1);
3038 // if there is no link data at all on the file!
3040 if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
3044 if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
3045 return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
3051 * load related objects
3053 * There are two ways to use this, one is to set up a <dbname>.links.ini file
3054 * into a static property named <dbname>.links and specifies the table joins,
3055 * the other highly dependent on naming columns 'correctly' :)
3056 * using colname = xxxxx_yyyyyy
3057 * xxxxxx = related table; (yyyyy = user defined..)
3058 * looks up table xxxxx, for value id=$this->xxxxx
3059 * stores it in $this->_xxxxx_yyyyy
3060 * you can change what object vars the links are stored in by
3061 * changeing the format parameter
3064 * @param string format (default _%s) where %s is the table name.
3065 * @author Tim White <tim@cyface.com>
3067 * @return boolean , true on success
3069 function getLinks($format = '_%s')
3072 // get table will load the options.
3073 if ($this->_link_loaded) {
3076 $this->_link_loaded = false;
3077 $cols = $this->table();
3078 $links = $this->links();
3083 foreach($links as $key => $match) {
3084 list($table,$link) = explode(':', $match);
3085 $k = sprintf($format, str_replace('.', '_', $key));
3086 // makes sure that '.' is the end of the key;
3087 if ($p = strpos($key,'.')) {
3088 $key = substr($key, 0, $p);
3091 $this->$k = $this->getLink($key, $table, $link);
3093 if (is_object($this->$k)) {
3097 $this->_link_loaded = $loaded;
3100 // this is the autonaming stuff..
3101 // it sends the column name down to getLink and lets that sort it out..
3102 // if there is a links file then it is not used!
3103 // IT IS DEPRECIATED!!!! - USE
3104 if (!is_null($links)) {
3109 foreach (array_keys($cols) as $key) {
3110 if (!($p = strpos($key, '_'))) {
3113 // does the table exist.
3114 $k =sprintf($format, $key);
3115 $this->$k = $this->getLink($key);
3116 if (is_object($this->$k)) {
3120 $this->_link_loaded = $loaded;
3125 * return name from related object
3127 * There are two ways to use this, one is to set up a <dbname>.links.ini file
3128 * into a static property named <dbname>.links and specifies the table joins,
3129 * the other is highly dependant on naming columns 'correctly' :)
3131 * NOTE: the naming convention is depreciated!!! - use links.ini
3133 * using colname = xxxxx_yyyyyy
3134 * xxxxxx = related table; (yyyyy = user defined..)
3135 * looks up table xxxxx, for value id=$this->xxxxx
3136 * stores it in $this->_xxxxx_yyyyy
3138 * you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
3141 * @param string $row either row or row.xxxxx
3142 * @param string $table name of table to look up value in
3143 * @param string $link name of column in other table to match
3144 * @author Tim White <tim@cyface.com>
3146 * @return mixed object on success
3148 function getLink($row, $table = null, $link = false)
3152 // GUESS THE LINKED TABLE.. (if found - recursevly call self)
3154 if ($table === null) {
3155 $links = $this->links();
3157 if (is_array($links)) {
3160 list($table,$link) = explode(':', $links[$row]);
3161 if ($p = strpos($row,".")) {
3162 $row = substr($row,0,$p);
3164 return $this->getLink($row,$table,$link);
3169 "getLink: $row is not defined as a link (normally this is ok)",
3170 DB_DATAOBJECT_ERROR_NODATA);
3173 return $r;// technically a possible error condition?
3176 // use the old _ method - this shouldnt happen if called via getLinks()
3177 if (!($p = strpos($row, '_'))) {
3181 $table = substr($row, 0, $p);
3182 return $this->getLink($row, $table);
3189 if (!isset($this->$row)) {
3190 $this->raiseError("getLink: row not set $row", DB_DATAOBJECT_ERROR_NODATA);
3194 // check to see if we know anything about this table..
3196 $obj = $this->factory($table);
3198 if (!is_a($obj,'DB_DataObject')) {
3200 "getLink:Could not find class for row $row, table $table",
3201 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3205 if ($obj->get($link, $this->$row)) {
3211 if ($obj->get($this->$row)) {
3220 * Fetch an array of related objects. This should be used in conjunction with a <dbname>.links.ini file configuration (see the introduction on linking for details on this).
3221 * You may also use this with all parameters to specify, the column and related table.
3222 * This is highly dependant on naming columns 'correctly' :)
3223 * using colname = xxxxx_yyyyyy
3224 * xxxxxx = related table; (yyyyy = user defined..)
3225 * looks up table xxxxx, for value id=$this->xxxxx
3226 * stores it in $this->_xxxxx_yyyyy
3229 * @param string $column - either column or column.xxxxx
3230 * @param string $table - name of table to look up value in
3231 * @return array - array of results (empty array on failure)
3233 * Example - Getting the related objects
3235 * $person = new DataObjects_Person;
3237 * $children = $person->getLinkArray('children');
3239 * echo 'There are ', count($children), ' descendant(s):<br />';
3240 * foreach ($children as $child) {
3241 * echo $child->name, '<br />';
3245 function &getLinkArray($row, $table = null)
3250 $links = $this->links();
3252 if (is_array($links)) {
3253 if (!isset($links[$row])) {
3257 list($table,$link) = explode(':',$links[$row]);
3259 if (!($p = strpos($row,'_'))) {
3262 $table = substr($row,0,$p);
3266 $c = $this->factory($table);
3268 if (!is_a($c,'DB_DataObject')) {
3270 "getLinkArray:Could not find class for row $row, table $table",
3271 DB_DATAOBJECT_ERROR_INVALIDCONFIG
3276 // if the user defined method list exists - use it...
3277 if (method_exists($c, 'listFind')) {
3278 $c->listFind($this->id);
3282 while ($c->fetch()) {
3289 * unionAdd - adds another dataobject to this, building a unioned query.
3292 * $doTable1 = DB_DataObject::factory("table1");
3293 * $doTable2 = DB_DataObject::factory("table2");
3295 * $doTable1->selectAdd();
3296 * $doTable1->selectAdd("col1,col2");
3297 * $doTable1->whereAdd("col1 > 100");
3298 * $doTable1->orderBy("col1");
3300 * $doTable2->selectAdd();
3301 * $doTable2->selectAdd("col1, col2");
3302 * $doTable2->whereAdd("col2 = 'v'");
3304 * $doTable1->unionAdd($doTable2);
3305 * $doTable1->find();
3307 * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
3310 * @param $obj object|false the union object or false to reset
3311 * @param optional $is_all string 'ALL' to do all.
3312 * @returns $obj object|array the added object, or old list if reset.
3315 function unionAdd($obj,$is_all= '')
3317 if ($obj === false) {
3318 $ret = $this->_query['unions'];
3319 $this->_query['unions'] = array();
3322 $this->_query['unions'][] = array($obj, 'UNION ' . $is_all . ' ') ;
3329 * The JOIN condition
3337 * joinAdd - adds another dataobject to this, building a joined query.
3339 * example (requires links.ini to be set up correctly)
3340 * // get all the images for product 24
3341 * $i = new DataObject_Image();
3342 * $pi = new DataObjects_Product_image();
3343 * $pi->product_id = 24; // set the product id to 24
3344 * $i->joinAdd($pi); // add the product_image connectoin
3346 * while ($i->fetch()) {
3349 * // an example with 2 joins
3350 * // get all the images linked with products or productgroups
3351 * $i = new DataObject_Image();
3352 * $pi = new DataObject_Product_image();
3353 * $pgi = new DataObject_Productgroup_image();
3355 * $i->joinAdd($pgi);
3357 * while ($i->fetch()) {
3362 * @param optional $obj object |array the joining object (no value resets the join)
3363 * If you use an array here it should be in the format:
3364 * array('local_column','remotetable:remote_column');
3365 * if remotetable does not have a definition, you should
3366 * use @ to hide the include error message..
3369 * @param optional $joinType string | array
3370 * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
3371 * just select ... from a,b,c with no join and
3372 * links are added as where items.
3374 * If second Argument is array, it is assumed to be an associative
3375 * array with arguments matching below = eg.
3376 * 'joinType' => 'INNER',
3379 * 'useWhereAsOn' => false,
3381 * @param optional $joinAs string if you want to select the table as anther name
3382 * useful when you want to select multiple columsn
3383 * from a secondary table.
3385 * @param optional $joinCol string The column on This objects table to match (needed
3386 * if this table links to the child object in
3387 * multiple places eg.
3388 * user->friend (is a link to another user)
3389 * user->mother (is a link to another user..)
3391 * optional 'useWhereAsOn' bool default false;
3392 * convert the where argments from the object being added
3393 * into ON arguments.
3398 * @author Stijn de Reede <sjr@gmx.co.uk>
3400 function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
3402 global $_DB_DATAOBJECT;
3403 if ($obj === false) {
3408 //echo '<PRE>'; print_r(func_get_args());
3409 $useWhereAsOn = false;
3410 // support for 2nd argument as an array of options
3411 if (is_array($joinType)) {
3412 // new options can now go in here... (dont forget to document them)
3413 $useWhereAsOn = !empty($joinType['useWhereAsOn']);
3414 $joinCol = isset($joinType['joinCol']) ? $joinType['joinCol'] : $joinCol;
3415 $joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
3416 $joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
3418 // support for array as first argument
3419 // this assumes that you dont have a links.ini for the specified table.
3420 // and it doesnt exist as am extended dataobject!! - experimental.
3422 $ofield = false; // object field
3423 $tfield = false; // this field
3425 if (is_array($obj)) {
3427 list($toTable,$ofield) = explode(':',$obj[1]);
3428 $obj = DB_DataObject::factory($toTable);
3430 if (!$obj || is_a($obj,'PEAR_Error')) {
3431 $obj = new DB_DataObject;
3432 $obj->__table = $toTable;
3435 // set the table items to nothing.. - eg. do not try and match
3436 // things in the child table...???
3440 if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
3441 return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
3443 /* make sure $this->_database is set. */
3445 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3448 /// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
3450 /* otherwise see if there are any links from this table to the obj. */
3451 //print_r($this->links());
3452 if (($ofield === false) && ($links = $this->links())) {
3453 // this enables for support for arrays of links in ini file.
3454 // link contains this_column[] = linked_table:linked_column
3456 // link contains this_column = linked_table:linked_column
3457 foreach ($links as $k => $linkVar) {
3459 if (!is_array($linkVar)) {
3460 $linkVar = array($linkVar);
3462 foreach($linkVar as $v) {
3466 /* link contains {this column} = {linked table}:{linked column} */
3467 $ar = explode(':', $v);
3468 // Feature Request #4266 - Allow joins with multiple keys
3469 if (strpos($k, ',') !== false) {
3470 $k = explode(',', $k);
3472 if (strpos($ar[1], ',') !== false) {
3473 $ar[1] = explode(',', $ar[1]);
3476 if ($ar[0] != $obj->__table) {
3479 if ($joinCol !== false) {
3480 if ($k == $joinCol) {
3496 /* look up the links for obj table */
3497 //print_r($obj->links());
3498 if (!$ofield && ($olinks = $obj->links())) {
3500 foreach ($olinks as $k => $linkVar) {
3501 /* link contains {this column} = array ( {linked table}:{linked column} )*/
3502 if (!is_array($linkVar)) {
3503 $linkVar = array($linkVar);
3505 foreach($linkVar as $v) {
3507 /* link contains {this column} = {linked table}:{linked column} */
3508 $ar = explode(':', $v);
3510 // Feature Request #4266 - Allow joins with multiple keys
3511 $links_key_array = strpos($k,',');
3512 if ($links_key_array !== false) {
3513 $k = explode(',', $k);
3516 $ar_array = strpos($ar[1],',');
3517 if ($ar_array !== false) {
3518 $ar[1] = explode(',', $ar[1]);
3521 if ($ar[0] != $this->__table) {
3525 // you have explictly specified the column
3526 // and the col is listed here..
3527 // not sure if 1:1 table could cause probs here..
3529 if ($joinCol !== false) {
3531 "joinAdd: You cannot target a join column in the " .
3532 "'link from' table ({$obj->__table}). " .
3533 "Either remove the fourth argument to joinAdd() ".
3534 "({$joinCol}), or alter your links.ini file.",
3535 DB_DATAOBJECT_ERROR_NODATA);
3547 // finally if these two table have column names that match do a join by default on them
3549 if (($ofield === false) && $joinCol) {
3554 /* did I find a conneciton between them? */
3556 if ($ofield === false) {
3558 "joinAdd: {$obj->__table} has no link with {$this->__table}",
3559 DB_DATAOBJECT_ERROR_NODATA);
3562 $joinType = strtoupper($joinType);
3564 // we default to joining as the same name (this is remvoed later..)
3566 if ($joinAs === false) {
3567 $joinAs = $obj->__table;
3570 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
3571 $options = $_DB_DATAOBJECT['CONFIG'];
3573 // not sure how portable adding database prefixes is..
3574 $objTable = $quoteIdentifiers ?
3575 $DB->quoteIdentifier($obj->__table) :
3579 if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
3580 $dbPrefix = ($quoteIdentifiers
3581 ? $DB->quoteIdentifier($obj->_database)
3582 : $obj->_database) . '.';
3585 // if they are the same, then dont add a prefix...
3586 if ($obj->_database == $this->_database) {
3589 // as far as we know only mysql supports database prefixes..
3590 // prefixing the database name is now the default behaviour,
3591 // as it enables joining mutiple columns from multiple databases...
3593 // prefix database (quoted if neccessary..)
3594 $objTable = $dbPrefix . $objTable;
3598 // if obj only a dataobject - eg. no extended class has been defined..
3599 // it obvioulsy cant work out what child elements might exist...
3600 // until we get on the fly querying of tables..
3601 // note: we have already checked that it is_a(db_dataobject earlier)
3602 if ( strtolower(get_class($obj)) != 'db_dataobject') {
3604 // now add where conditions for anything that is set in the object
3608 $items = $obj->table();
3609 // will return an array if no items..
3611 // only fail if we where expecting it to work (eg. not joined on a array)
3615 "joinAdd: No table definition for {$obj->__table}",
3616 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3620 $ignore_null = !isset($options['disable_null_strings'])
3621 || !is_string($options['disable_null_strings'])
3622 || strtolower($options['disable_null_strings']) !== 'full' ;
3625 foreach($items as $k => $v) {
3626 if (!isset($obj->$k) && $ignore_null) {
3630 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
3632 if (DB_DataObject::_is_null($obj,$k)) {
3633 $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
3637 if ($v & DB_DATAOBJECT_STR) {
3638 $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
3639 ($v & DB_DATAOBJECT_BOOL) ?
3640 // this is thanks to the braindead idea of postgres to
3641 // use t/f for boolean.
3642 (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
3647 if (is_numeric($obj->$k)) {
3648 $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
3652 if (is_a($obj->$k,'DB_DataObject_Cast')) {
3653 $value = $obj->$k->toString($v,$DB);
3654 if (PEAR::isError($value)) {
3655 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
3658 $obj->whereAdd("{$joinAs}.{$kSql} = $value");
3663 /* this is probably an error condition! */
3664 $obj->whereAdd("{$joinAs}.{$kSql} = 0");
3666 if ($this->_query === false) {
3668 "joinAdd can not be run from a object that has had a query run on it,
3669 clone the object or create a new one and use setFrom()",
3670 DB_DATAOBJECT_ERROR_INVALIDARGS);
3675 // and finally merge the whereAdd from the child..
3676 if ($obj->_query['condition']) {
3677 $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
3679 if (!$useWhereAsOn) {
3680 $this->whereAdd($cond);
3687 // nested (join of joined objects..)
3690 // postgres allows nested queries, with ()'s
3691 // not sure what the results are with other databases..
3692 // may be unpredictable..
3693 if (in_array($DB->dsn["phptype"],array('pgsql'))) {
3694 $objTable = "($objTable {$obj->_join})";
3696 $appendJoin = $obj->_join;
3702 // add the joinee object's conditions to the ON clause instead of the WHERE clause
3703 if ($useWhereAsOn && strlen($cond)) {
3704 $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
3709 $table = $this->__table;
3711 if ($quoteIdentifiers) {
3712 $joinAs = $DB->quoteIdentifier($joinAs);
3713 $table = $DB->quoteIdentifier($table);
3714 $ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
3715 $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
3717 // add database prefix if they are different databases
3721 $addJoinAs = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->__table) : $obj->__table) != $joinAs;
3723 // join table a AS b - is only supported by a few databases and is probably not needed
3724 // , however since it makes the whole Statement alot clearer we are leaving it in
3725 // for those databases.
3726 $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
3729 $joinAs = $dbPrefix . $joinAs;
3733 switch ($joinType) {
3736 case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
3738 // Feature Request #4266 - Allow joins with multiple keys
3739 $jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3740 //$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3741 if (is_array($ofield)) {
3742 $key_count = count($ofield);
3743 for($i = 0; $i < $key_count; $i++) {
3745 $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
3748 $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
3751 $jadd .= ' ' . $appendJoin . ' ';
3753 $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
3755 // jadd avaliable for debugging join build.
3757 $this->_join .= $jadd;
3760 case '': // this is just a standard multitable select..
3761 $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
3762 $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
3771 * Copies items that are in the table definitions from an
3772 * array or object into the current object
3773 * will not override key values.
3776 * @param array | object $from
3777 * @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
3778 * @param boolean $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
3780 * @return true on success or array of key=>setValue error message
3782 function setFrom($from, $format = '%s', $skipEmpty=false)
3784 global $_DB_DATAOBJECT;
3785 $keys = $this->keys();
3786 $items = $this->table();
3789 "setFrom:Could not find table definition for {$this->__table}",
3790 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3793 $overload_return = array();
3794 foreach (array_keys($items) as $k) {
3795 if (in_array($k,$keys)) {
3796 continue; // dont overwrite keys
3799 continue; // ignore empty keys!!! what
3802 $chk = is_object($from) &&
3803 (version_compare(phpversion(), "5.1.0" , ">=") ?
3804 property_exists($from, sprintf($format,$k)) : // php5.1
3805 array_key_exists( sprintf($format,$k), get_class_vars($from)) //older
3807 // if from has property ($format($k)
3809 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3810 if (method_exists($this,'set'.$kk)) {
3811 $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
3812 if (is_string($ret)) {
3813 $overload_return[$k] = $ret;
3817 $this->$k = $from->{sprintf($format,$k)};
3821 if (is_object($from)) {
3825 if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
3829 if (!isset($from[sprintf($format,$k)]) && !DB_DataObject::_is_null($from, sprintf($format,$k))) {
3833 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3834 if (method_exists($this,'set'. $kk)) {
3835 $ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
3836 if (is_string($ret)) {
3837 $overload_return[$k] = $ret;
3841 if (is_object($from[sprintf($format,$k)])) {
3844 if (is_array($from[sprintf($format,$k)])) {
3847 $ret = $this->fromValue($k,$from[sprintf($format,$k)]);
3848 if ($ret !== true) {
3849 $overload_return[$k] = 'Not A Valid Value';
3851 //$this->$k = $from[sprintf($format,$k)];
3853 if ($overload_return) {
3854 return $overload_return;
3860 * Returns an associative array from the current data
3861 * (kind of oblivates the idea behind DataObjects, but
3862 * is usefull if you use it with things like QuickForms.
3864 * you can use the format to return things like user[key]
3865 * by sending it $object->toArray('user[%s]')
3867 * will also return links converted to arrays.
3869 * @param string sprintf format for array
3870 * @param bool empty only return elemnts that have a value set.
3873 * @return array of key => value for row
3876 function toArray($format = '%s', $hideEmpty = false)
3878 global $_DB_DATAOBJECT;
3880 $rf = ($this->_resultFields !== false) ? $this->_resultFields :
3881 (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ? $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
3882 $ar = ($rf !== false) ?
3883 array_merge($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid],$this->table()) :
3886 foreach($ar as $k=>$v) {
3888 if (!isset($this->$k)) {
3890 $ret[sprintf($format,$k)] = '';
3894 // call the overloaded getXXXX() method. - except getLink and getLinks
3895 if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
3896 $ret[sprintf($format,$k)] = $this->{'get'.$k}();
3899 // should this call toValue() ???
3900 $ret[sprintf($format,$k)] = $this->$k;
3902 if (!$this->_link_loaded) {
3905 foreach($this->_link_loaded as $k) {
3906 $ret[sprintf($format,$k)] = $this->$k->toArray();
3914 * validate the values of the object (usually prior to inserting/updating..)
3916 * Note: This was always intended as a simple validation routine.
3917 * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
3919 * This should be moved to another class: DB_DataObject_Validate
3920 * FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
3923 * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
3926 * - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
3927 * - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
3928 * These methods should return
3929 * true = everything ok
3930 * false|object = something is wrong!
3932 * - This method loads and uses the PEAR Validate Class.
3936 * @return array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
3940 global $_DB_DATAOBJECT;
3941 require_once 'Validate.php';
3942 $table = $this->table();
3944 $seq = $this->sequenceKey();
3945 $options = $_DB_DATAOBJECT['CONFIG'];
3946 foreach($table as $key => $val) {
3949 // call user defined validation always...
3950 $method = "Validate" . ucfirst($key);
3951 if (method_exists($this, $method)) {
3952 $ret[$key] = $this->$method();
3956 // if not null - and it's not set.......
3958 if ($val & DB_DATAOBJECT_NOTNULL && DB_DataObject::_is_null($this, $key)) {
3959 // dont check empty sequence key values..
3960 if (($key == $seq[0]) && ($seq[1] == true)) {
3968 if (DB_DataObject::_is_null($this, $key)) {
3969 if ($val & DB_DATAOBJECT_NOTNULL) {
3970 $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
3977 // ignore things that are not set. ?
3979 if (!isset($this->$key)) {
3983 // if the string is empty.. assume it is ok..
3984 if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
3988 // dont try and validate cast objects - assume they are problably ok..
3989 if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
3992 // at this point if you have set something to an object, and it's not expected
3993 // the Validate will probably break!!... - rightly so! (your design is broken,
3994 // so issuing a runtime error like PEAR_Error is probably not appropriate..
3997 // todo: date time.....
3998 case ($val & DB_DATAOBJECT_STR):
3999 $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
4001 case ($val & DB_DATAOBJECT_INT):
4002 $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
4006 // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
4007 foreach ($ret as $key => $val) {
4008 if ($val !== true) {
4012 return true; // everything is OK.
4016 * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
4019 * @return object The DB connection
4021 function &getDatabaseConnection()
4023 global $_DB_DATAOBJECT;
4025 if (($e = $this->_connect()) !== true) {
4028 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4032 return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
4037 * Gets the DB result object related to the objects active query
4038 * - so you can use funky pear stuff with it - like pager for example.. :)
4041 * @return object The DB result object
4044 function &getDatabaseResult()
4046 global $_DB_DATAOBJECT;
4048 if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4052 return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
4056 * Overload Extension support
4057 * - enables setCOLNAME/getCOLNAME
4058 * if you define a set/get method for the item it will be called.
4059 * otherwise it will just return/set the value.
4060 * NOTE this currently means that a few Names are NO-NO's
4061 * eg. links,link,linksarray, from, Databaseconnection,databaseresult
4064 * - set is automatically called by setFrom.
4065 * - get is automatically called by toArray()
4067 * setters return true on success. = strings on failure
4068 * getters return the value!
4070 * this fires off trigger_error - if any problems.. pear_error,
4071 * has problems with 4.3.2RC2 here
4079 function _call($method,$params,&$return) {
4081 //$this->debug("ATTEMPTING OVERLOAD? $method");
4082 // ignore constructors : - mm
4083 if (strtolower($method) == strtolower(get_class($this))) {
4086 $type = strtolower(substr($method,0,3));
4087 $class = get_class($this);
4088 if (($type != 'set') && ($type != 'get')) {
4094 // deal with naming conflick of setFrom = this is messy ATM!
4096 if (strtolower($method) == 'set_from') {
4097 $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
4101 $element = substr($method,3);
4103 // dont you just love php's case insensitivity!!!!
4105 $array = array_keys(get_class_vars($class));
4106 /* php5 version which segfaults on 5.0.3 */
4107 if (class_exists('ReflectionClass')) {
4108 $reflection = new ReflectionClass($class);
4109 $array = array_keys($reflection->getdefaultProperties());
4112 if (!in_array($element,$array)) {
4114 foreach($array as $k) {
4115 $case[strtolower($k)] = $k;
4117 if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
4118 trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
4119 $element = strtolower($element);
4122 // does it really exist?
4123 if (!isset($case[$element])) {
4126 // use the mundged case
4127 $element = $case[$element]; // real case !
4131 if ($type == 'get') {
4132 $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
4137 $return = $this->fromValue($element, $params[0]);
4146 * standard set* implementation.
4148 * takes data and uses it to set dates/strings etc.
4149 * normally called from __call..
4152 * date = using (standard time format, or unixtimestamp).... so you could create a method :
4153 * function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
4155 * time = using strtotime
4156 * datetime = using same as date - accepts iso standard or unixtimestamp.
4157 * string = typecast only..
4159 * TODO: add formater:: eg. d/m/Y for date! ???
4161 * @param string column of database
4162 * @param mixed value to assign
4164 * @return true| false (False on error)
4166 * @see DB_DataObject::_call
4170 function fromValue($col,$value)
4172 global $_DB_DATAOBJECT;
4173 $options = $_DB_DATAOBJECT['CONFIG'];
4174 $cols = $this->table();
4175 // dont know anything about this col..
4176 if (!isset($cols[$col])) {
4177 $this->$col = $value;
4180 //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
4182 // set to null and column is can be null...
4183 case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
4184 case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
4185 $this->$col = $value;
4188 // fail on setting null on a not null field..
4189 case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value,false)):
4193 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
4194 // empty values get set to '' (which is inserted/updated as NULl
4199 if (is_numeric($value)) {
4200 $this->$col = date('Y-m-d H:i:s', $value);
4204 // eak... - no way to validate date time otherwise...
4205 $this->$col = (string) $value;
4208 case ($cols[$col] & DB_DATAOBJECT_DATE):
4209 // empty values get set to '' (which is inserted/updated as NULl
4216 if (is_numeric($value)) {
4217 $this->$col = date('Y-m-d',$value);
4222 require_once 'Date.php';
4223 $x = new Date($value);
4224 $this->$col = $x->format("%Y-%m-%d");
4227 case ($cols[$col] & DB_DATAOBJECT_TIME):
4228 // empty values get set to '' (which is inserted/updated as NULl
4233 $guess = strtotime($value);
4235 $this->$col = date('H:i:s', $guess);
4236 return $return = true;
4238 // otherwise an error in type...
4241 case ($cols[$col] & DB_DATAOBJECT_STR):
4243 $this->$col = (string) $value;
4246 // todo : floats numerics and ints...
4248 $this->$col = $value;
4256 * standard get* implementation.
4259 * supported formaters:
4260 * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
4261 * numbers : %02d (eg. sprintf)
4262 * NOTE you will get unexpected results with times like 0000-00-00 !!!
4266 * @param string column of database
4267 * @param format foramt
4269 * @return true Description
4271 * @see DB_DataObject::_call(),strftime(),Date::format()
4273 function toValue($col,$format = null)
4275 if (is_null($format)) {
4278 $cols = $this->table();
4280 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
4284 $guess = strtotime($this->$col);
4286 return strftime($format, $guess);
4288 // eak... - no way to validate date time otherwise...
4290 case ($cols[$col] & DB_DATAOBJECT_DATE):
4294 $guess = strtotime($this->$col);
4296 return strftime($format,$guess);
4299 require_once 'Date.php';
4300 $x = new Date($this->$col);
4301 return $x->format($format);
4303 case ($cols[$col] & DB_DATAOBJECT_TIME):
4307 $guess = strtotime($this->$col);
4309 return strftime($format, $guess);
4311 // otherwise an error in type...
4314 case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
4318 require_once 'Date.php';
4320 $x = new Date($this->$col);
4322 return $x->format($format);
4325 case ($cols[$col] & DB_DATAOBJECT_BOOL):
4327 if ($cols[$col] & DB_DATAOBJECT_STR) {
4329 return ($this->$col === 't');
4331 return (bool) $this->$col;
4335 return sprintf($format,$this->col);
4342 /* ----------------------- Debugger ------------------ */
4345 * Debugger. - use this in your extended classes to output debugging information.
4347 * Uses DB_DataObject::DebugLevel(x) to turn it on
4349 * @param string $message - message to output
4350 * @param string $logtype - bold at start
4351 * @param string $level - output level
4355 function debug($message, $logtype = 0, $level = 1)
4357 global $_DB_DATAOBJECT;
4359 if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
4360 (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
4363 // this is a bit flaky due to php's wonderfull class passing around crap..
4364 // but it's about as good as it gets..
4365 $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
4367 if (!is_string($message)) {
4368 $message = print_r($message,true);
4370 if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
4371 return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
4374 if (!ini_get('html_errors')) {
4375 echo "$class : $logtype : $message\n";
4379 if (!is_string($message)) {
4380 $message = print_r($message,true);
4382 $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
4383 echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
4387 * sets and returns debug level
4388 * eg. DB_DataObject::debugLevel(4);
4390 * @param int $v level
4394 function debugLevel($v = null)
4396 global $_DB_DATAOBJECT;
4397 if (empty($_DB_DATAOBJECT['CONFIG'])) {
4398 DB_DataObject::_loadConfig();
4401 $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4402 $_DB_DATAOBJECT['CONFIG']['debug'] = $v;
4405 return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4409 * Last Error that has occured
4410 * - use $this->_lastError or
4411 * $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4414 * @var object PEAR_Error (or false)
4416 var $_lastError = false;
4419 * Default error handling is to create a pear error, but never return it.
4420 * if you need to handle errors you should look at setting the PEAR_Error callback
4421 * this is due to the fact it would wreck havoc on the internal methods!
4423 * @param int $message message
4424 * @param int $type type
4425 * @param int $behaviour behaviour (die or continue!);
4427 * @return error object
4429 function raiseError($message, $type = null, $behaviour = null)
4431 global $_DB_DATAOBJECT;
4433 if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
4436 $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4438 // this will never work totally with PHP's object model.
4439 // as this is passed on static calls (like staticGet in our case)
4441 if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
4442 $this->_lastError = $error;
4445 $_DB_DATAOBJECT['LASTERROR'] = $error;
4447 // no checks for production here?....... - we log errors before we throw them.
4448 DB_DataObject::debug($message,'ERROR',1);
4451 if (PEAR::isError($message)) {
4454 require_once 'DB/DataObject/Error.php';
4455 $error = PEAR::raiseError($message, $type, $behaviour,
4456 $opts=null, $userinfo=null, 'DB_DataObject_Error'
4464 * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
4466 * After Profiling DB_DataObject, I discoved that the debug calls where taking
4467 * considerable time (well 0.1 ms), so this should stop those calls happening. as
4468 * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
4469 * THIS STILL NEEDS FURTHER INVESTIGATION
4472 * @return object an error object
4474 function _loadConfig()
4476 global $_DB_DATAOBJECT;
4478 $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
4483 * Free global arrays associated with this object.
4491 global $_DB_DATAOBJECT;
4493 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
4494 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
4496 if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4497 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
4499 // clear the staticGet cache as well.
4500 $this->_clear_cache();
4501 // this is a huge bug in DB!
4502 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4503 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
4506 if (is_array($this->_link_loaded)) {
4507 foreach ($this->_link_loaded as $do) {
4515 * Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
4516 * If the value is a string set to "null" and the "disable_null_strings" option is not set to
4517 * true, then the value is considered to be null.
4518 * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to
4519 * the value "full", then it will also be considered null. - this can not differenticate between not set
4522 * @param object|array $obj_or_ar
4523 * @param string|false $prop prperty
4526 * @return bool object
4528 function _is_null($obj_or_ar , $prop)
4530 global $_DB_DATAOBJECT;
4533 $isset = $prop === false ? isset($obj_or_ar) :
4534 (is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
4537 ($prop === false ? $obj_or_ar :
4538 (is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
4543 $options = $_DB_DATAOBJECT['CONFIG'];
4545 $null_strings = !isset($options['disable_null_strings'])
4546 || $options['disable_null_strings'] === false;
4548 $crazy_null = isset($options['disable_null_strings'])
4549 && is_string($options['disable_null_strings'])
4550 && strtolower($options['disable_null_strings'] === 'full');
4552 if ( $null_strings && $isset && is_string($value) && (strtolower($value) === 'null') ) {
4556 if ( $crazy_null && !$isset ) {
4565 /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
4567 function _get_table() { return $this->table(); }
4568 function _get_keys() { return $this->keys(); }
4574 // technially 4.3.2RC1 was broken!!
4575 // looks like 4.3.3 may have problems too....
4576 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
4578 if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
4579 if (version_compare( phpversion(), "5") < 0) {
4580 overload('DB_DataObject');
4582 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;