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 336751 2015-05-12 04:39:50Z 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 // these two are BC/FC handlers for call in PHP4/5
182 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
184 class DB_DataObject_Overload
186 function __call($method,$args)
189 $this->_call($method,$args,$return);
194 return array_keys(get_object_vars($this)) ;
198 class DB_DataObject_Overload {}
209 * @package DB_DataObject
210 * @author Alan Knowles <alan@akbkhome.com>
214 class DB_DataObject extends DB_DataObject_Overload
217 * The Version - use this to check feature changes
222 var $_DB_DataObject_version = "1.11.3";
225 * The Database table (used by table extends)
230 var $__table = ''; // database table
233 * The Number of rows returned from a query
238 var $N = 0; // Number of rows returned from a query
240 /* ============================================================= */
241 /* Major Public Methods */
242 /* (designed to be optionally then called with parent::method()) */
243 /* ============================================================= */
247 * Get a result using key, value.
250 * $object->get("ID",1234);
251 * Returns Number of rows located (usually 1) for success,
252 * and puts all the table columns into this classes variables
254 * see the fetch example on how to extend this.
256 * if no value is entered, it is assumed that $key is a value
257 * and get will then use the first key in keys()
260 * @param string $k column
261 * @param string $v value
263 * @return int No. of rows
265 function get($k = null, $v = null)
267 global $_DB_DATAOBJECT;
268 if (empty($_DB_DATAOBJECT['CONFIG'])) {
269 DB_DataObject::_loadConfig();
275 $keys = $this->keys();
277 $this->raiseError("No Keys available for {$this->tableName()}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
282 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
283 $this->debug("$k $v " .print_r($keys,true), "GET");
287 $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
291 return $this->find(1);
295 * Get the value of the primary id
297 * While I normally use 'id' as the PRIMARY KEY value, some database use
298 * {table}_id as the column name.
300 * To save a bit of typing,
308 $keys = $this->keys();
310 $this->raiseError("No Keys available for {$this->tableName()}",
311 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
315 if (empty($this->$k)) { // we do not
316 $this->raiseError("pid() called on Object where primary key value not available",
317 DB_DATAOBJECT_ERROR_NODATA);
326 * build the basic select query.
331 function _build_select()
333 global $_DB_DATAOBJECT;
334 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
335 if ($quoteIdentifiers) {
337 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
339 $tn = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName()) ;
340 if (!empty($this->_query['derive_table']) && !empty($this->_query['derive_select']) ) {
342 // this is a derived select..
343 // not much support in the api yet..
346 $this->_query['derive_select']
348 $this->_query['data_select'] . " \n" .
349 " FROM $tn " . $this->_query['useindex'] . " \n" .
350 $this->_join . " \n" .
351 $this->_query['condition'] . " \n" .
352 $this->_query['group_by'] . " \n" .
353 $this->_query['having'] . " \n" .
354 ') ' . $this->_query['derive_table'];
364 $this->_query['data_select'] . " \n" .
365 " FROM $tn " . $this->_query['useindex'] . " \n" .
366 $this->_join . " \n" .
367 $this->_query['condition'] . " \n" .
368 $this->_query['group_by'] . " \n" .
369 $this->_query['having'] . " \n";
376 * find results, either normal or crosstable
380 * $object = new mytable();
385 * will set $object->N to number of rows, and expects next command to fetch rows
386 * will return $object->N
388 * if an error occurs $object->N will be set to false and return value will also be false;
389 * if numRows is not supported it will
392 * @param boolean $n Fetch first result
394 * @return mixed (number of rows returned, or true if numRows fetching is not supported)
396 function find($n = false)
398 global $_DB_DATAOBJECT;
399 if ($this->_query === false) {
401 "You cannot do two queries on the same object (copy it before finding)",
402 DB_DATAOBJECT_ERROR_INVALIDARGS);
406 if (empty($_DB_DATAOBJECT['CONFIG'])) {
407 DB_DataObject::_loadConfig();
410 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
411 $this->debug($n, "find",1);
413 if (!strlen($this->tableName())) {
414 // xdebug can backtrace this!
415 trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
418 $query_before = $this->_query;
419 $this->_build_condition($this->table()) ;
423 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
426 $sql = $this->_build_select();
428 foreach ($this->_query['unions'] as $union_ar) {
429 $sql .= $union_ar[1] . $union_ar[0]->_build_select() . " \n";
432 $sql .= $this->_query['order_by'] . " \n";
435 /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
436 if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
437 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
438 /* PEAR DB specific */
440 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
441 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
444 /* theoretically MDB2! */
445 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
446 $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
451 $err = $this->_query($sql);
452 if (is_a($err,'PEAR_Error')) {
456 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
457 $this->debug("CHECK autofetchd $n", "find", 1);
463 if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
464 // clear up memory if nothing found!?
465 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
468 if ($n && $this->N > 0 ) {
469 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
470 $this->debug("ABOUT TO AUTOFETCH", "find", 1);
472 $fs = $this->fetch();
473 // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
474 // - hence find() also returns false..
475 $ret = ($ret === true) ? $fs : $ret;
477 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
478 $this->debug("DONE", "find", 1);
480 $this->_query = $query_before;
485 * fetches next row into this objects var's
487 * returns 1 on success 0 on failure
492 * $object = new mytable();
493 * $object->name = "fred";
496 * while ($object->fetch()) {
498 * $store[] = $object; // builds an array of object lines.
501 * to add features to a fetch
502 * function fetch () {
503 * $ret = parent::fetch();
504 * $this->date_formated = date('dmY',$this->date);
509 * @return boolean on success
514 global $_DB_DATAOBJECT;
515 if (empty($_DB_DATAOBJECT['CONFIG'])) {
516 DB_DataObject::_loadConfig();
518 if (empty($this->N)) {
519 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
520 $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
525 if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
526 !is_object($result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
528 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
529 $this->debug('fetched on object after fetch completed (no results found)');
535 $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
536 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
537 $this->debug(serialize($array),"FETCH");
540 // fetched after last row..
541 if ($array === null) {
542 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
543 $t= explode(' ',microtime());
545 $this->debug("Last Data Fetch'ed after " .
546 ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
550 // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
551 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
553 // we need to keep a copy of resultfields locally so toArray() still works
554 // however we dont want to keep it in the global cache..
556 if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
557 $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
558 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
560 // this is probably end of data!!
561 //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
564 // make sure resultFields is always empty..
565 $this->_resultFields = false;
567 if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
568 // note: we dont declare this to keep the print_r size down.
569 $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
571 $replace = array('.', ' ');
572 foreach($array as $k=>$v) {
573 // use strpos as str_replace is slow.
574 $kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
575 $k : str_replace($replace, '_', $k);
577 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
578 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
580 $this->$kk = $array[$k];
584 $this->_link_loaded=false;
585 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
586 $this->debug("{$this->tableName()} DONE", "fetchrow",2);
588 if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
589 $this->_query = false;
596 * fetches all results as an array,
598 * return format is dependant on args.
599 * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
601 * A) Array of values (eg. a list of 'id')
603 * $x = DB_DataObject::factory('mytable');
604 * $x->whereAdd('something = 1')
605 * $ar = $x->fetchAll('id');
606 * -- returns array(1,2,3,4,5)
608 * B) Array of values (not from table)
610 * $x = DB_DataObject::factory('mytable');
611 * $x->whereAdd('something = 1');
613 * $x->selectAdd('distinct(group_id) as group_id');
614 * $ar = $x->fetchAll('group_id');
615 * -- returns array(1,2,3,4,5)
617 * C) A key=>value associative array
619 * $x = DB_DataObject::factory('mytable');
620 * $x->whereAdd('something = 1')
621 * $ar = $x->fetchAll('id','name');
622 * -- returns array(1=>'fred',2=>'blogs',3=> .......
624 * D) array of objects
625 * $x = DB_DataObject::factory('mytable');
626 * $x->whereAdd('something = 1');
627 * $ar = $x->fetchAll();
629 * E) array of arrays (for example)
630 * $x = DB_DataObject::factory('mytable');
631 * $x->whereAdd('something = 1');
632 * $ar = $x->fetchAll(false,false,'toArray');
635 * @param string|false $k key
636 * @param string|false $v value
637 * @param string|false $method method to call on each result to get array value (eg. 'toArray')
639 * @return array format dependant on arguments, may be empty
641 function fetchAll($k= false, $v = false, $method = false)
643 // should it even do this!!!?!?
645 ( // only do this is we have not been explicit..
646 empty($this->_query['data_select']) ||
647 ($this->_query['data_select'] == '*')
651 $this->selectAdd($k);
653 $this->selectAdd($v);
659 while ($this->fetch()) {
661 $ret[$this->$k] = $this->$v;
664 $ret[] = $k === false ?
665 ($method == false ? clone($this) : $this->$method())
674 * Adds a condition to the WHERE statement, defaults to AND
676 * $object->whereAdd(); //reset or cleaer ewhwer
677 * $object->whereAdd("ID > 20");
678 * $object->whereAdd("age > 20","OR");
680 * @param string $cond condition
681 * @param string $logic optional logic "OR" (defaults to "AND")
683 * @return string|PEAR::Error - previous condition or Error when invalid args found
685 function whereAdd($cond = false, $logic = 'AND')
687 // for PHP5.2.3 - there is a bug with setting array properties of an object.
688 $_query = $this->_query;
690 if (!isset($this->_query) || ($_query === false)) {
691 return $this->raiseError(
692 "You cannot do two queries on the same object (clone it before finding)",
693 DB_DATAOBJECT_ERROR_INVALIDARGS);
696 if ($cond === false) {
697 $r = $this->_query['condition'];
698 $_query['condition'] = '';
699 $this->_query = $_query;
700 return preg_replace('/^\s+WHERE\s+/','',$r);
702 // check input...= 0 or ' ' == error!
704 return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
706 $r = $_query['condition'];
707 if ($_query['condition']) {
708 $_query['condition'] .= " {$logic} ( {$cond} )";
709 $this->_query = $_query;
712 $_query['condition'] = " WHERE ( {$cond} ) ";
713 $this->_query = $_query;
718 * Adds a 'IN' condition to the WHERE statement
720 * $object->whereAddIn('id', $array, 'int'); //minimal usage
721 * $object->whereAddIn('price', $array, 'float', 'OR'); // cast to float, and call whereAdd with 'OR'
722 * $object->whereAddIn('name', $array, 'string'); // quote strings
724 * @param string $key key column to match
725 * @param array $list list of values to match
726 * @param string $type string|int|integer|float|bool cast to type.
727 * @param string $logic optional logic to call whereAdd with eg. "OR" (defaults to "AND")
729 * @return string|PEAR::Error - previous condition or Error when invalid args found
731 function whereAddIn($key, $list, $type, $logic = 'AND')
734 if ($key[0] == '!') {
736 $key = substr($key, 1);
738 // fix type for short entry.
739 $type = $type == 'int' ? 'integer' : $type;
741 if ($type == 'string') {
746 foreach($list as $k) {
748 $ar[] = $type == 'string' ? $this->_quote($k) : $k;
752 return $not ? $this->_query['condition'] : $this->whereAdd("1=0");
754 return $this->whereAdd("$key $not IN (". implode(',', $ar). ')', $logic );
760 * Adds a order by condition
762 * $object->orderBy(); //clears order by
763 * $object->orderBy("ID");
764 * $object->orderBy("ID,age");
766 * @param string $order Order
768 * @return none|PEAR::Error - invalid args only
770 function orderBy($order = false)
772 if ($this->_query === false) {
774 "You cannot do two queries on the same object (copy it before finding)",
775 DB_DATAOBJECT_ERROR_INVALIDARGS);
778 if ($order === false) {
779 $this->_query['order_by'] = '';
782 // check input...= 0 or ' ' == error!
784 return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
787 if (!$this->_query['order_by']) {
788 $this->_query['order_by'] = " ORDER BY {$order} ";
791 $this->_query['order_by'] .= " , {$order}";
795 * Adds a group by condition
797 * $object->groupBy(); //reset the grouping
798 * $object->groupBy("ID DESC");
799 * $object->groupBy("ID,age");
801 * @param string $group Grouping
803 * @return none|PEAR::Error - invalid args only
805 function groupBy($group = false)
807 if ($this->_query === false) {
809 "You cannot do two queries on the same object (copy it before finding)",
810 DB_DATAOBJECT_ERROR_INVALIDARGS);
813 if ($group === false) {
814 $this->_query['group_by'] = '';
817 // check input...= 0 or ' ' == error!
819 return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
823 if (!$this->_query['group_by']) {
824 $this->_query['group_by'] = " GROUP BY {$group} ";
827 $this->_query['group_by'] .= " , {$group}";
831 * Adds a having clause
833 * $object->having(); //reset the grouping
834 * $object->having("sum(value) > 0 ");
836 * @param string $having condition
838 * @return none|PEAR::Error - invalid args only
840 function having($having = false)
842 if ($this->_query === false) {
844 "You cannot do two queries on the same object (copy it before finding)",
845 DB_DATAOBJECT_ERROR_INVALIDARGS);
848 if ($having === false) {
849 $this->_query['having'] = '';
852 // check input...= 0 or ' ' == error!
853 if (!trim($having)) {
854 return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
858 if (!$this->_query['having']) {
859 $this->_query['having'] = " HAVING {$having} ";
862 $this->_query['having'] .= " AND {$having}";
868 * $object->useIndex(); //reset the use Index
869 * $object->useIndex("some_index");
871 * Note do not put unfiltered user input into theis method.
872 * This is mysql specific at present? - might need altering to support other databases.
874 * @param string|array $index index or indexes to use.
876 * @return none|PEAR::Error - invalid args only
878 function useIndex($index = false)
880 if ($this->_query === false) {
882 "You cannot do two queries on the same object (copy it before finding)",
883 DB_DATAOBJECT_ERROR_INVALIDARGS);
886 if ($index=== false) {
887 $this->_query['useindex'] = '';
890 // check input...= 0 or ' ' == error!
891 if ((is_string($index) && !trim($index)) || (is_array($index) && !count($index)) ) {
892 return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
894 $index = is_array($index) ? implode(', ', $index) : $index;
896 if (!$this->_query['useindex']) {
897 $this->_query['useindex'] = " USE INDEX ({$index}) ";
900 $this->_query['useindex'] = substr($this->_query['useindex'],0, -2) . ", {$index}) ";
905 * $boject->limit(); // clear limit
906 * $object->limit(12);
907 * $object->limit(12,10);
909 * Note this will emit an error on databases other than mysql/postgress
910 * as there is no 'clean way' to implement it. - you should consider refering to
911 * your database manual to decide how you want to implement it.
913 * @param string $a limit start (or number), or blank to reset
914 * @param string $b number
916 * @return none|PEAR::Error - invalid args only
918 function limit($a = null, $b = null)
920 if ($this->_query === false) {
922 "You cannot do two queries on the same object (copy it before finding)",
923 DB_DATAOBJECT_ERROR_INVALIDARGS);
928 $this->_query['limit_start'] = '';
929 $this->_query['limit_count'] = '';
932 // check input...= 0 or ' ' == error!
933 if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
934 || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
935 return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
937 global $_DB_DATAOBJECT;
939 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
941 $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
942 $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
947 * Adds a select columns
949 * $object->selectAdd(); // resets select to nothing!
950 * $object->selectAdd("*"); // default select
951 * $object->selectAdd("unixtime(DATE) as udate");
952 * $object->selectAdd("DATE");
954 * to prepend distict:
955 * $object->selectAdd('distinct ' . $object->selectAdd());
959 * @return mixed null or old string if you reset it.
961 function selectAdd($k = null)
963 if ($this->_query === false) {
965 "You cannot do two queries on the same object (copy it before finding)",
966 DB_DATAOBJECT_ERROR_INVALIDARGS);
970 $old = $this->_query['data_select'];
971 $this->_query['data_select'] = '';
975 // check input...= 0 or ' ' == error!
977 return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
980 if ($this->_query['data_select']) {
981 $this->_query['data_select'] .= ', ';
983 $this->_query['data_select'] .= " $k ";
986 * Adds multiple Columns or objects to select with formating.
988 * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
989 * // note with null it will also clear the '*' default select
990 * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
991 * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
992 * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
993 * objectTableName.colnameA as prefix_colnameA
995 * @param array|object|null the array or object to take column names from.
996 * @param string format in sprintf format (use %s for the colname)
997 * @param string table name eg. if you have joinAdd'd or send $from as an array.
1001 function selectAs($from = null,$format = '%s',$tableName=false)
1003 global $_DB_DATAOBJECT;
1005 if ($this->_query === false) {
1007 "You cannot do two queries on the same object (copy it before finding)",
1008 DB_DATAOBJECT_ERROR_INVALIDARGS);
1012 if ($from === null) {
1019 $table = $this->tableName();
1020 if (is_object($from)) {
1021 $table = $from->tableName();
1022 $from = array_keys($from->table());
1025 if ($tableName !== false) {
1026 $table = $tableName;
1029 if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
1031 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1032 $s = $DB->quoteIdentifier($s);
1033 $format = $DB->quoteIdentifier($format);
1035 foreach ($from as $k) {
1036 $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
1038 $this->_query['data_select'] .= "\n";
1041 * Insert the current objects variables into the database
1043 * Returns the ID of the inserted element (if auto increment or sequences are used.)
1047 * Designed to be extended
1049 * $object = new mytable();
1050 * $object->name = "fred";
1051 * echo $object->insert();
1054 * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
1058 global $_DB_DATAOBJECT;
1060 // we need to write to the connection (For nextid) - so us the real
1061 // one not, a copyied on (as ret-by-ref fails with overload!)
1063 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
1067 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1069 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1071 $items = $this->table();
1074 $this->raiseError("insert:No table definition for {$this->tableName()}",
1075 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1078 $options = $_DB_DATAOBJECT['CONFIG'];
1085 $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]) ?
1086 $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] :
1087 $this->sequenceKey();
1089 $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
1090 $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
1091 $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
1093 $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
1096 // nativeSequences or Sequences..
1098 // big check for using sequences
1100 if (($key !== false) && !$useNative) {
1103 $keyvalue = $DB->nextId($this->tableName());
1105 $f = $DB->getOption('seqname_format');
1106 $DB->setOption('seqname_format','%s');
1107 $keyvalue = $DB->nextId($seq);
1108 $DB->setOption('seqname_format',$f);
1110 if (PEAR::isError($keyvalue)) {
1111 $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1114 $this->$key = $keyvalue;
1117 // if we haven't set disable_null_strings to "full"
1118 $ignore_null = !isset($options['disable_null_strings'])
1119 || !is_string($options['disable_null_strings'])
1120 || strtolower($options['disable_null_strings']) !== 'full' ;
1123 foreach($items as $k => $v) {
1125 // if we are using autoincrement - skip the column...
1126 if ($key && ($k == $key) && $useNative) {
1131 // Ignore INTEGERS which aren't set to a value - or empty string..
1132 if ( (!isset($this->$k) || ($v == 1 && $this->$k === ''))
1137 // dont insert data into mysql timestamps
1138 // use query() if you really want to do this!!!!
1139 if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1148 $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
1150 if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
1151 $value = $this->$k->toString($v,$DB);
1152 if (PEAR::isError($value)) {
1153 $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
1161 if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
1162 $rightq .= " NULL ";
1165 // DATE is empty... on a col. that can be null..
1166 // note: this may be usefull for time as well..
1168 (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
1169 !($v & DB_DATAOBJECT_NOTNULL)) {
1171 $rightq .= " NULL ";
1176 if ($v & DB_DATAOBJECT_STR) {
1177 $rightq .= $this->_quote((string) (
1178 ($v & DB_DATAOBJECT_BOOL) ?
1179 // this is thanks to the braindead idea of postgres to
1180 // use t/f for boolean.
1181 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
1186 if (is_numeric($this->$k)) {
1187 $rightq .=" {$this->$k} ";
1190 /* flag up string values - only at debug level... !!!??? */
1191 if (is_object($this->$k) || is_array($this->$k)) {
1192 $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k,true),'ERROR');
1195 // at present we only cast to integers
1196 // - V2 may store additional data about float/int
1197 $rightq .= ' ' . intval($this->$k) . ' ';
1201 // not sure why we let empty insert here.. - I guess to generate a blank row..
1204 if ($leftq || $useNative) {
1205 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
1208 if (($dbtype == 'pgsql') && empty($leftq)) {
1209 $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
1211 $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
1217 if (PEAR::isError($r)) {
1218 $this->raiseError($r);
1227 // now do we have an integer key!
1229 if ($key && $useNative) {
1233 $method = "{$dbtype}_insert_id";
1234 $this->$key = $method(
1235 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
1240 // note this is not really thread safe - you should wrapp it with
1241 // transactions = eg.
1242 // $db->query('BEGIN');
1244 // $db->query('COMMIT');
1245 $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1246 $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
1247 $mssql_key = $DB->$method("SELECT @@IDENTITY");
1248 if (PEAR::isError($mssql_key)) {
1249 $this->raiseError($mssql_key);
1252 $this->$key = $mssql_key;
1257 $seq = $DB->getSequenceName(strtolower($this->tableName()));
1259 $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1260 $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
1261 $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
1264 if (PEAR::isError($pgsql_key)) {
1265 $this->raiseError($pgsql_key);
1268 $this->$key = $pgsql_key;
1272 $this->$key = array_shift (
1275 "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
1276 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
1288 if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
1289 $this->_clear_cache();
1296 $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1301 * Updates current objects variables into the database
1302 * uses the keys() to decide how to update
1303 * Returns the true on success
1307 * $object = DB_DataObject::factory('mytable');
1308 * $object->get("ID",234);
1309 * $object->email="testing@test.com";
1310 * if(!$object->update())
1311 * echo "UPDATE FAILED";
1313 * to only update changed items :
1314 * $dataobject->get(132);
1315 * $original = $dataobject; // clone/copy it..
1316 * $dataobject->setFrom($_POST);
1317 * if ($dataobject->validate()) {
1318 * $dataobject->update($original);
1319 * } // otherwise an error...
1321 * performing global updates:
1322 * $object = DB_DataObject::factory('mytable');
1323 * $object->status = "dead";
1324 * $object->whereAdd('age > 150');
1325 * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
1327 * @param object dataobject (optional) | DB_DATAOBJECT_WHEREADD_ONLY - used to only update changed items.
1329 * @return int rows affected or false on failure
1331 function update($dataObject = false)
1333 global $_DB_DATAOBJECT;
1334 // connect will load the config!
1338 $original_query = $this->_query;
1340 $items = $this->table();
1342 // only apply update against sequence key if it is set?????
1344 $seq = $this->sequenceKey();
1345 if ($seq[0] !== false) {
1346 $keys = array($seq[0]);
1347 if (!isset($this->{$keys[0]}) && $dataObject !== true) {
1348 $this->raiseError("update: trying to perform an update without
1349 the key set, and argument to update is not
1350 DB_DATAOBJECT_WHEREADD_ONLY
1351 ". print_r(array('seq' => $seq , 'keys'=>$keys), true), DB_DATAOBJECT_ERROR_INVALIDARGS);
1355 $keys = $this->keys();
1360 $this->raiseError("update:No table definition for {$this->tableName()}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1367 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1368 $dbtype = $DB->dsn["phptype"];
1369 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1370 $options = $_DB_DATAOBJECT['CONFIG'];
1373 $ignore_null = !isset($options['disable_null_strings'])
1374 || !is_string($options['disable_null_strings'])
1375 || strtolower($options['disable_null_strings']) !== 'full' ;
1378 foreach($items as $k => $v) {
1380 // I think this is ignoring empty vlalues
1381 if ((!isset($this->$k) || ($v == 1 && $this->$k === ''))
1386 // ignore stuff thats
1388 // dont write things that havent changed..
1389 if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
1393 // - dont write keys to left.!!!
1394 if (in_array($k,$keys)) {
1398 // dont insert data into mysql timestamps
1399 // use query() if you really want to do this!!!!
1400 if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1409 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
1411 if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
1412 $value = $this->$k->toString($v,$DB);
1413 if (PEAR::isError($value)) {
1414 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
1417 $settings .= "$kSql = $value ";
1421 // special values ... at least null is handled...
1422 if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
1423 $settings .= "$kSql = NULL ";
1426 // DATE is empty... on a col. that can be null..
1427 // note: this may be usefull for time as well..
1429 (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
1430 !($v & DB_DATAOBJECT_NOTNULL)) {
1432 $settings .= "$kSql = NULL ";
1437 if ($v & DB_DATAOBJECT_STR) {
1438 $settings .= "$kSql = ". $this->_quote((string) (
1439 ($v & DB_DATAOBJECT_BOOL) ?
1440 // this is thanks to the braindead idea of postgres to
1441 // use t/f for boolean.
1442 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
1447 if (is_numeric($this->$k)) {
1448 $settings .= "$kSql = {$this->$k} ";
1451 // at present we only cast to integers
1452 // - V2 may store additional data about float/int
1453 $settings .= "$kSql = " . intval($this->$k) . ' ';
1457 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1458 $this->debug("got keys as ".serialize($keys),3);
1460 if ($dataObject !== true) {
1461 $this->_build_condition($items,$keys);
1463 // prevent wiping out of data!
1464 if (empty($this->_query['condition'])) {
1465 $this->raiseError("update: global table update not available
1466 do \$do->whereAdd('1=1'); if you really want to do that.
1467 ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1474 // echo " $settings, $this->condition ";
1475 if ($settings && isset($this->_query) && $this->_query['condition']) {
1477 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
1479 $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
1481 // restore original query conditions.
1482 $this->_query = $original_query;
1484 if (PEAR::isError($r)) {
1485 $this->raiseError($r);
1492 $this->_clear_cache();
1495 // restore original query conditions.
1496 $this->_query = $original_query;
1498 // if you manually specified a dataobject, and there where no changes - then it's ok..
1499 if ($dataObject !== false) {
1504 "update: No Data specifed for query $settings , {$this->_query['condition']}",
1505 DB_DATAOBJECT_ERROR_NODATA);
1510 * Deletes items from table which match current objects variables
1512 * Returns the true on success
1516 * Designed to be extended
1518 * $object = new mytable();
1520 * echo $object->delete(); // builds a conditon
1522 * $object = new mytable();
1523 * $object->whereAdd('age > 12');
1524 * $object->limit(1);
1525 * $object->orderBy('age DESC');
1526 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
1528 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1529 * we will build the condition only using the whereAdd's. Default is to
1530 * build the condition only using the object parameters.
1533 * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
1535 function delete($useWhere = false)
1537 global $_DB_DATAOBJECT;
1538 // connect will load the config!
1540 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1541 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1543 $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
1547 $keys = $this->keys();
1548 $this->_query = array(); // as it's probably unset!
1549 $this->_query['condition'] = ''; // default behaviour not to use where condition
1550 $this->_build_condition($this->table(),$keys);
1551 // if primary keys are not set then use data from rest of object.
1552 if (!$this->_query['condition']) {
1553 $this->_build_condition($this->table(),array(),$keys);
1559 // don't delete without a condition
1560 if (($this->_query !== false) && $this->_query['condition']) {
1562 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
1564 // using a joined delete. - with useWhere..
1565 $sql .= (!empty($this->_join) && $useWhere) ?
1566 "{$table} FROM {$table} {$this->_join} " :
1569 $sql .= $this->_query['condition']. $extra_cond;
1573 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
1575 if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
1576 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
1578 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
1582 $DB->setLimit( $this->_query['limit_count'],$this->_query['limit_start']);
1588 $r = $this->_query($sql);
1591 if (PEAR::isError($r)) {
1592 $this->raiseError($r);
1598 $this->_clear_cache();
1601 $this->raiseError("delete: No condition specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1607 * fetches a specific row into this object variables
1609 * Not recommended - better to use fetch()
1611 * Returens true on success
1613 * @param int $row row
1615 * @return boolean true on success
1617 function fetchRow($row = null)
1619 global $_DB_DATAOBJECT;
1620 if (empty($_DB_DATAOBJECT['CONFIG'])) {
1621 $this->_loadConfig();
1623 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1624 $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow",3);
1626 if (!$this->tableName()) {
1627 $this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1630 if ($row === null) {
1631 $this->raiseError("fetchrow: No row specified", DB_DATAOBJECT_ERROR_INVALIDARGS);
1635 $this->raiseError("fetchrow: No results avaiable", DB_DATAOBJECT_ERROR_NODATA);
1638 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1639 $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow",3);
1643 $result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
1644 $array = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC,$row);
1645 if (!is_array($array)) {
1646 $this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
1649 $replace = array('.', ' ');
1650 foreach($array as $k => $v) {
1651 // use strpos as str_replace is slow.
1652 $kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
1653 $k : str_replace($replace, '_', $k);
1655 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1656 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
1658 $this->$kk = $array[$k];
1661 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1662 $this->debug("{$this->tableName()} DONE", "fetchrow", 3);
1668 * Find the number of results from a simple query
1672 * $object = new mytable();
1673 * $object->name = "fred";
1674 * echo $object->count();
1675 * echo $object->count(true); // dont use object vars.
1676 * echo $object->count('distinct mycol'); count distinct mycol.
1677 * echo $object->count('distinct mycol',true); // dont use object vars.
1678 * echo $object->count('distinct'); // count distinct id (eg. the primary key)
1681 * @param bool|string (optional)
1682 * (true|false => see below not on whereAddonly)
1684 * "DISTINCT" => does a distinct count on the tables 'key' column
1685 * otherwise => normally it counts primary keys - you can use
1686 * this to do things like $do->count('distinct mycol');
1688 * @param bool $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1689 * we will build the condition only using the whereAdd's. Default is to
1690 * build the condition using the object parameters as well.
1695 function count($countWhat = false,$whereAddOnly = false)
1697 global $_DB_DATAOBJECT;
1699 if (is_bool($countWhat)) {
1700 $whereAddOnly = $countWhat;
1704 $items = $t->table();
1706 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1709 if (!isset($t->_query)) {
1711 "You cannot do run count after you have run fetch()",
1712 DB_DATAOBJECT_ERROR_INVALIDARGS);
1716 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1719 if (!$whereAddOnly && $items) {
1720 $t->_build_condition($items);
1722 $keys = $this->keys();
1724 if (empty($keys[0]) && (!is_string($countWhat) || (strtoupper($countWhat) == 'DISTINCT'))) {
1726 "You cannot do run count without keys - use \$do->count('id'), or use \$do->count('distinct id')';",
1727 DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
1731 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
1732 $key_col = empty($keys[0]) ? '' : (($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]));
1733 $as = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
1735 // support distinct on default keys.
1736 $countWhat = (strtoupper($countWhat) == 'DISTINCT') ?
1737 "DISTINCT {$table}.{$key_col}" : $countWhat;
1739 $countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
1742 "SELECT count({$countWhat}) as $as
1743 FROM $table {$t->_join} {$t->_query['condition']}");
1744 if (PEAR::isError($r)) {
1748 $result = $_DB_DATAOBJECT['RESULTS'][$t->_DB_resultid];
1749 $l = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ORDERED);
1750 // free the results - essential on oracle.
1752 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1753 $this->debug('Count returned '. $l[0] ,1);
1759 * sends raw query to database
1761 * Since _query has to be a private 'non overwriteable method', this is a relay
1763 * @param string $string SQL Query
1765 * @return void or DB_Error
1767 function query($string)
1769 return $this->_query($string);
1774 * an escape wrapper around DB->escapeSimple()
1775 * can be used when adding manual queries or clauses
1777 * $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
1779 * @param string $string value to be escaped
1780 * @param bool $likeEscape escapes % and _ as well. - so like queries can be protected.
1784 function escape($string, $likeEscape=false)
1786 global $_DB_DATAOBJECT;
1788 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1789 // mdb2 uses escape...
1790 $dd = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
1791 $ret = ($dd == 'DB') ? $DB->escapeSimple($string) : $DB->escape($string);
1793 $ret = str_replace(array('_','%'), array('\_','\%'), $ret);
1799 /* ==================================================== */
1800 /* Major Private Vars */
1801 /* ==================================================== */
1804 * The Database connection dsn (as described in the PEAR DB)
1805 * only used really if you are writing a very simple application/test..
1806 * try not to use this - it is better stored in configuration files..
1811 var $_database_dsn = '';
1814 * The Database connection id (md5 sum of databasedsn)
1819 var $_database_dsn_md5 = '';
1823 * created in __connection
1828 var $_database = '';
1834 * This replaces alot of the private variables
1835 * used to build a query, it is unset after find() is run.
1842 var $_query = array(
1843 'condition' => '', // the WHERE condition
1844 'group_by' => '', // the GROUP BY condition
1845 'order_by' => '', // the ORDER BY condition
1846 'having' => '', // the HAVING condition
1847 'useindex' => '', // the USE INDEX condition
1848 'limit_start' => '', // the LIMIT condition
1849 'limit_count' => '', // the LIMIT condition
1850 'data_select' => '*', // the columns to be SELECTed
1851 'unions' => array(), // the added unions,
1852 'derive_table' => '', // derived table name (BETA)
1853 'derive_select' => '', // derived table select (BETA)
1860 * Database result id (references global $_DB_DataObject[results]
1868 * ResultFields - on the last call to fetch(), resultfields is sent here,
1869 * so we can clean up the memory.
1874 var $_resultFields = false;
1877 /* ============================================================== */
1878 /* Table definition layer (started of very private but 'came out'*/
1879 /* ============================================================== */
1882 * Autoload or manually load the table definitions
1886 * DB_DataObject::databaseStructure( 'databasename',
1887 * parse_ini_file('mydb.ini',true),
1888 * parse_ini_file('mydb.link.ini',true));
1890 * obviously you dont have to use ini files.. (just return array similar to ini files..)
1892 * It should append to the table structure array
1895 * @param optional string name of database to assign / read
1896 * @param optional array structure of database, and keys
1897 * @param optional array table links
1900 * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
1901 * or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
1903 function databaseStructure()
1906 global $_DB_DATAOBJECT;
1910 if ($args = func_get_args()) {
1912 if (count($args) == 1) {
1914 // this returns all the tables and their structure..
1915 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1916 $this->debug("Loading Generator as databaseStructure called with args",1);
1919 $x = new DB_DataObject;
1920 $x->_database = $args[0];
1922 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1924 $tables = $DB->getListOf('tables');
1925 class_exists('DB_DataObject_Generator') ? '' :
1926 require_once 'DB/DataObject/Generator.php';
1928 foreach($tables as $table) {
1929 $y = new DB_DataObject_Generator;
1930 $y->fillTableSchema($x->_database,$table);
1932 return $_DB_DATAOBJECT['INI'][$x->_database];
1935 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
1936 $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
1938 if (isset($args[1])) {
1939 $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
1940 $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
1949 if (!$this->_database) {
1954 // if this table is already loaded this table..
1955 if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
1959 // initialize the ini data.. if empt..
1960 if (empty($_DB_DATAOBJECT['INI'][$this->_database])) {
1961 $_DB_DATAOBJECT['INI'][$this->_database] = array();
1964 if (empty($_DB_DATAOBJECT['CONFIG'])) {
1965 DB_DataObject::_loadConfig();
1968 // we do not have the data for this table yet...
1970 // if we are configured to use the proxy..
1972 if ( !empty($_DB_DATAOBJECT['CONFIG']['proxy']) ) {
1973 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1974 $this->debug("Loading Generator to fetch Schema",1);
1976 class_exists('DB_DataObject_Generator') ? '' :
1977 require_once 'DB/DataObject/Generator.php';
1980 $x = new DB_DataObject_Generator;
1981 $x->fillTableSchema($this->_database,$this->tableName());
1988 // if you supply this with arguments, then it will take those
1989 // as the database and links array...
1991 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
1992 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
1995 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
1996 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
1997 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
1998 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
2002 $_DB_DATAOBJECT['INI'][$this->_database] = array();
2003 foreach ($schemas as $ini) {
2004 if (file_exists($ini) && is_file($ini)) {
2006 $_DB_DATAOBJECT['INI'][$this->_database] = array_merge(
2007 $_DB_DATAOBJECT['INI'][$this->_database],
2008 parse_ini_file($ini, true)
2011 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2012 if (!is_readable ($ini)) {
2013 $this->debug("ini file is not readable: $ini","databaseStructure",1);
2015 $this->debug("Loaded ini file: $ini","databaseStructure",1);
2019 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2020 $this->debug("Missing ini file: $ini","databaseStructure",1);
2025 // are table name lowecased..
2026 if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
2027 foreach($_DB_DATAOBJECT['INI'][$this->_database] as $k=>$v) {
2028 // results in duplicate cols.. but not a big issue..
2029 $_DB_DATAOBJECT['INI'][$this->_database][strtolower($k)] = $v;
2034 // now have we loaded the structure..
2036 if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
2039 // - if not try building it..
2040 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
2041 class_exists('DB_DataObject_Generator') ? '' :
2042 require_once 'DB/DataObject/Generator.php';
2044 $x = new DB_DataObject_Generator;
2045 $x->fillTableSchema($this->_database,$this->tableName());
2046 // should this fail!!!???
2049 $this->debug("Cant find database schema: {$this->_database}/{$this->tableName()} \n".
2050 "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
2051 // we have to die here!! - it causes chaos if we dont (including looping forever!)
2052 $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);
2062 * Return or assign the name of the current table
2065 * @param string optinal table name to set
2067 * @return string The name of the current table
2069 function tableName()
2071 global $_DB_DATAOBJECT;
2072 $args = func_get_args();
2074 $this->__table = $args[0];
2076 if (empty($this->__table)) {
2079 if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
2080 return strtolower($this->__table);
2082 return $this->__table;
2086 * Return or assign the name of the current database
2088 * @param string optional database name to set
2090 * @return string The name of the current database
2094 $args = func_get_args();
2096 $this->_database = $args[0];
2101 return $this->_database;
2105 * get/set an associative array of table columns
2108 * @param array key=>type array
2109 * @return array (associative)
2114 // for temporary storage of database fields..
2115 // note this is not declared as we dont want to bloat the print_r output
2116 $args = func_get_args();
2118 $this->_database_fields = $args[0];
2120 if (isset($this->_database_fields)) {
2121 return $this->_database_fields;
2125 global $_DB_DATAOBJECT;
2126 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2130 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
2131 return $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()];
2134 $this->databaseStructure();
2138 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
2139 $ret = $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()];
2146 * get/set an array of table primary keys
2148 * set usage: $do->keys('id','code');
2150 * This is defined in the table definition if it gets it wrong,
2151 * or you do not want to use ini tables, you can override this.
2152 * @param string optional set the key
2153 * @param * optional set more keys
2159 // for temporary storage of database fields..
2160 // note this is not declared as we dont want to bloat the print_r output
2161 $args = func_get_args();
2163 $this->_database_keys = $args;
2165 if (isset($this->_database_keys)) {
2166 return $this->_database_keys;
2169 global $_DB_DATAOBJECT;
2170 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2173 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
2174 return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"]);
2176 $this->databaseStructure();
2178 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
2179 return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"]);
2184 * get/set an sequence key
2186 * by default it returns the first key from keys()
2187 * set usage: $do->sequenceKey('id',true);
2189 * override this to return array(false,false) if table has no real sequence key.
2191 * @param string optional the key sequence/autoinc. key
2192 * @param boolean optional use native increment. default false
2193 * @param false|string optional native sequence name
2195 * @return array (column,use_native,sequence_name)
2197 function sequenceKey()
2199 global $_DB_DATAOBJECT;
2202 if (!$this->_database) {
2206 if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
2207 $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
2211 $args = func_get_args();
2213 $args[1] = isset($args[1]) ? $args[1] : false;
2214 $args[2] = isset($args[2]) ? $args[2] : false;
2215 $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = $args;
2217 if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()])) {
2218 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()];
2220 // end call setting (eg. $do->sequenceKeys(a,b,c); )
2225 $keys = $this->keys();
2227 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]
2228 = array(false,false,false);
2232 $table = $this->table();
2234 $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
2242 if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->tableName()])) {
2243 $seqname = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->tableName()];
2244 if (strpos($seqname,':') !== false) {
2245 list($usekey,$seqname) = explode(':',$seqname);
2250 // if the key is not an integer - then it's not a sequence or native
2251 if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
2252 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,false);
2256 if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
2257 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
2258 if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
2259 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
2261 if (is_string($ignore)) {
2262 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
2264 if (in_array($this->tableName(),$ignore)) {
2265 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
2270 $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"];
2272 // if you are using an old ini file - go back to old behaviour...
2273 if (is_numeric($realkeys[$usekey])) {
2274 $realkeys[$usekey] = 'N';
2277 // multiple unique primary keys without a native sequence...
2278 if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
2279 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
2281 // use native sequence keys...
2282 // technically postgres native here...
2283 // we need to get the new improved tabledata sorted out first.
2285 // support named sequence keys.. - currently postgres only..
2287 if ( in_array($dbtype , array('pgsql')) &&
2288 ($table[$usekey] & DB_DATAOBJECT_INT) &&
2289 isset($realkeys[$usekey]) && strlen($realkeys[$usekey]) > 1) {
2290 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,true, $realkeys[$usekey]);
2293 if ( in_array($dbtype , array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
2294 ($table[$usekey] & DB_DATAOBJECT_INT) &&
2295 isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
2297 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,true,$seqname);
2301 // if not a native autoinc, and we have not assumed all primary keys are sequence
2302 if (($realkeys[$usekey] != 'N') &&
2303 !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
2304 return array(false,false,false);
2309 // I assume it's going to try and be a nextval DB sequence.. (not native)
2310 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,false,$seqname);
2315 /* =========================================================== */
2316 /* Major Private Methods - the core part! */
2317 /* =========================================================== */
2322 * clear the cache values for this class - normally done on insert/update etc.
2327 function _clear_cache()
2329 global $_DB_DATAOBJECT;
2331 $class = strtolower(get_class($this));
2333 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2334 $this->debug("Clearing Cache for ".$class,1);
2337 if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
2338 unset($_DB_DATAOBJECT['CACHE'][$class]);
2344 * backend wrapper for quoting, as MDB2 and DB do it differently...
2347 * @return string quoted
2350 function _quote($str)
2352 global $_DB_DATAOBJECT;
2353 return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
2354 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
2355 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
2356 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
2361 * connects to the database
2364 * TODO: tidy this up - This has grown to support a number of connection options like
2365 * a) dynamic changing of ini file to change which database to connect to
2366 * b) multi data via the table_{$table} = dsn ini option
2367 * c) session based storage.
2370 * @return true | PEAR::error
2374 global $_DB_DATAOBJECT;
2375 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2376 $this->_loadConfig();
2378 // Set database driver for reference
2379 $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
2380 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
2382 // is it already connected ?
2383 if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2385 // connection is an error...
2386 if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2387 return $this->raiseError(
2388 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
2389 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2394 if (empty($this->_database)) {
2395 $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2396 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2398 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2399 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2400 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2404 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2405 && is_file($this->_database)) {
2406 $this->_database = basename($this->_database);
2408 if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase') {
2409 $this->_database = substr(basename($this->_database), 0, -4);
2413 // theoretically we have a md5, it's listed in connections and it's not an error.
2414 // so everything is ok!
2419 // it's not currently connected!
2420 // try and work out what to use for the dsn !
2422 $options= $_DB_DATAOBJECT['CONFIG'];
2423 // if the databse dsn dis defined in the object..
2424 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
2427 if (!$this->_database && !strlen($this->tableName())) {
2428 $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
2430 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2431 $this->debug("Checking for database specific ini ('{$this->_database}') : database_{$this->_database} in options","CONNECT");
2434 if ($this->_database && !empty($options["database_{$this->_database}"])) {
2435 $dsn = $options["database_{$this->_database}"];
2436 } else if (!empty($options['database'])) {
2437 $dsn = $options['database'];
2442 // if still no database...
2444 return $this->raiseError(
2445 "No database name / dsn found anywhere",
2446 DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
2452 if (is_string($dsn)) {
2453 $this->_database_dsn_md5 = md5($dsn);
2455 /// support array based dsn's
2456 $this->_database_dsn_md5 = md5(serialize($dsn));
2459 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2460 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2461 $this->debug("USING CACHED CONNECTION", "CONNECT",3);
2466 if (!$this->_database) {
2468 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2469 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2470 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2471 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2473 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2474 && is_file($this->_database))
2476 $this->_database = basename($this->_database);
2481 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2482 $this->debug("NEW CONNECTION TP DATABASE :" .$this->_database , "CONNECT",3);
2483 /* actualy make a connection */
2484 $this->debug(print_r($dsn,true) ." {$this->_database_dsn_md5}", "CONNECT",3);
2487 // Note this is verbose deliberatly!
2489 if ($db_driver == 'DB') {
2491 /* PEAR DB connect */
2493 // this allows the setings of compatibility on DB
2494 $db_options = PEAR::getStaticProperty('DB','options');
2495 require_once 'DB.php';
2497 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn,$db_options);
2499 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn);
2503 /* assumption is MDB2 */
2504 require_once 'MDB2.php';
2505 // this allows the setings of compatibility on MDB2
2506 $db_options = PEAR::getStaticProperty('MDB2','options');
2507 $db_options = is_array($db_options) ? $db_options : array();
2508 $db_options['portability'] = isset($db_options['portability'] )
2509 ? $db_options['portability'] : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
2510 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = MDB2::connect($dsn,$db_options);
2515 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2516 $this->debug(print_r($_DB_DATAOBJECT['CONNECTIONS'],true), "CONNECT",5);
2518 if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2519 $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED",5);
2520 return $this->raiseError(
2521 "Connect failed, turn on debugging to 5 see why",
2522 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2527 if (empty($this->_database)) {
2528 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2530 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2531 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2532 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2535 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2536 && is_file($this->_database))
2538 $this->_database = basename($this->_database);
2542 // Oracle need to optimize for portibility - not sure exactly what this does though :)
2548 * sends query to database - this is the private one that must work
2549 * - internal functions use this rather than $this->query()
2551 * @param string $string
2553 * @return mixed none or PEAR_Error
2555 function _query($string)
2557 global $_DB_DATAOBJECT;
2561 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2563 $options = $_DB_DATAOBJECT['CONFIG'];
2565 $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
2566 'DB': $_DB_DATAOBJECT['CONFIG']['db_driver'];
2568 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2569 $this->debug($string,$log="QUERY");
2574 strtoupper($string) == 'BEGIN' ||
2575 strtoupper($string) == 'START TRANSACTION'
2577 if ($_DB_driver == 'DB') {
2578 $DB->autoCommit(false);
2579 $DB->simpleQuery('BEGIN');
2581 $DB->beginTransaction();
2586 if (strtoupper($string) == 'COMMIT') {
2587 $res = $DB->commit();
2588 if ($_DB_driver == 'DB') {
2589 $DB->autoCommit(true);
2594 if (strtoupper($string) == 'ROLLBACK') {
2596 if ($_DB_driver == 'DB') {
2597 $DB->autoCommit(true);
2603 if (!empty($options['debug_ignore_updates']) &&
2604 (strtolower(substr(trim($string), 0, 6)) != 'select') &&
2605 (strtolower(substr(trim($string), 0, 4)) != 'show') &&
2606 (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
2608 $this->debug('Disabling Update as you are in debug mode');
2609 return $this->raiseError("Disabling Update as you are in debug mode", null) ;
2612 //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
2613 // this will only work when PEAR:DB supports it.
2614 //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
2618 $t= explode(' ',microtime());
2619 $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
2622 for ($tries = 0;$tries < 3;$tries++) {
2624 if ($_DB_driver == 'DB') {
2626 $result = $DB->query($string);
2628 switch (strtolower(substr(trim($string),0,6))) {
2633 $result = $DB->exec($string);
2637 $result = $DB->query($string);
2642 // see if we got a failure.. - try again a few times..
2643 if (!is_object($result) || !is_a($result,'PEAR_Error')) {
2646 if ($result->getCode() != -14) { // *DB_ERROR_NODBSELECTED
2647 break; // not a connection error..
2649 sleep(1); // wait before retyring..
2650 $DB->connect($DB->dsn);
2654 if (is_object($result) && is_a($result,'PEAR_Error')) {
2655 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2656 $this->debug($result->toString(), "Query Error",1 );
2659 return $this->raiseError($result);
2661 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2662 $t= explode(' ',microtime());
2663 $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
2664 $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query',1);
2666 switch (strtolower(substr(trim($string),0,6))) {
2670 if ($_DB_driver == 'DB') {
2672 return $DB->affectedRows();
2676 if (is_object($result)) {
2677 // lets hope that copying the result object is OK!
2679 $_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
2680 $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
2681 $this->_DB_resultid = $_DB_resultid;
2684 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2685 $this->debug(serialize($result), 'RESULT',5);
2687 if (method_exists($result, 'numRows')) {
2688 if ($_DB_driver == 'DB') {
2689 $DB->expectError(DB_ERROR_UNSUPPORTED);
2691 $DB->expectError(MDB2_ERROR_UNSUPPORTED);
2694 $this->N = $result->numRows();
2695 //var_dump($this->N);
2697 if (is_object($this->N) && is_a($this->N,'PEAR_Error')) {
2705 * Builds the WHERE based on the values of of this object
2707 * @param mixed $keys
2708 * @param array $filter (used by update to only uses keys in this filter list).
2709 * @param array $negative_filter (used by delete to prevent deleting using the keys mentioned..)
2713 function _build_condition($keys, $filter = array(),$negative_filter=array())
2715 global $_DB_DATAOBJECT;
2717 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2719 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
2720 $options = $_DB_DATAOBJECT['CONFIG'];
2722 // if we dont have query vars.. - reset them.
2723 if ($this->_query === false) {
2724 $x = new DB_DataObject;
2725 $this->_query= $x->_query;
2729 foreach($keys as $k => $v) {
2730 // index keys is an indexed array
2731 /* these filter checks are a bit suspicious..
2732 - need to check that update really wants to work this way */
2735 if (!in_array($k, $filter)) {
2739 if ($negative_filter) {
2740 if (in_array($k, $negative_filter)) {
2744 if (!isset($this->$k)) {
2748 $kSql = $quoteIdentifiers
2749 ? ( $DB->quoteIdentifier($this->tableName()) . '.' . $DB->quoteIdentifier($k) )
2750 : "{$this->tableName()}.{$k}";
2754 if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
2755 $dbtype = $DB->dsn["phptype"];
2756 $value = $this->$k->toString($v,$DB);
2757 if (PEAR::isError($value)) {
2758 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
2761 if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2762 $this->whereAdd(" $kSql IS NULL");
2765 $this->whereAdd(" $kSql = $value");
2769 if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
2770 $this->whereAdd(" $kSql IS NULL");
2775 if ($v & DB_DATAOBJECT_STR) {
2776 $this->whereAdd(" $kSql = " . $this->_quote((string) (
2777 ($v & DB_DATAOBJECT_BOOL) ?
2778 // this is thanks to the braindead idea of postgres to
2779 // use t/f for boolean.
2780 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
2785 if (is_numeric($this->$k)) {
2786 $this->whereAdd(" $kSql = {$this->$k}");
2789 /* this is probably an error condition! */
2790 $this->whereAdd(" $kSql = ".intval($this->$k));
2797 * classic factory method for loading a table class
2798 * usage: $do = DB_DataObject::factory('person')
2799 * WARNING - this may emit a include error if the file does not exist..
2800 * use @ to silence it (if you are sure it is acceptable)
2801 * eg. $do = @DB_DataObject::factory('person')
2803 * table name can bedatabasename/table
2804 * - and allow modular dataobjects to be written..
2805 * (this also helps proxy creation)
2807 * Experimental Support for Multi-Database factory eg. mydatabase.mytable
2810 * @param string $table tablename (use blank to create a new instance of the same class.)
2812 * @return DataObject|PEAR_Error
2817 static function factory($table = '')
2819 global $_DB_DATAOBJECT;
2822 // multi-database support.. - experimental.
2825 if (strpos( $table,'/') !== false ) {
2826 list($database,$table) = explode('.',$table, 2);
2830 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2831 DB_DataObject::_loadConfig();
2833 // no configuration available for database
2834 if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_'.$database])) {
2835 $do = new DB_DataObject();
2837 "unable to find database_{$database} in Configuration, It is required for factory with database"
2838 , 0, PEAR_ERROR_DIE );
2843 if ($table === '') {
2844 if (is_a($this,'DB_DataObject') && strlen($this->tableName())) {
2845 $table = $this->tableName();
2847 return DB_DataObject::raiseError(
2848 "factory did not recieve a table name",
2849 DB_DATAOBJECT_ERROR_INVALIDARGS);
2854 // does this need multi db support??
2855 $cp = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2856 explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']['class_prefix']) : '';
2860 // multiprefix support.
2861 $tbl = preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2862 if (is_array($cp)) {
2864 foreach($cp as $cpr) {
2865 $ce = substr(phpversion(),0,1) > 4 ? class_exists($cpr . $tbl,false) : class_exists($cpr . $tbl);
2867 $class = $cpr . $tbl;
2870 $class[] = $cpr . $tbl;
2874 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2878 $rclass = $ce ? $class : DB_DataObject::_autoloadClass($class, $table);
2879 // proxy = full|light
2880 if (!$rclass && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
2882 DB_DataObject::debug("FAILED TO Autoload $database.$table - using proxy.","FACTORY",1);
2885 $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
2886 // if you have loaded (some other way) - dont try and load it again..
2887 class_exists('DB_DataObject_Generator') ? '' :
2888 require_once 'DB/DataObject/Generator.php';
2890 $d = new DB_DataObject;
2892 $d->__table = $table;
2894 $ret = $d->_connect();
2895 if (is_object($ret) && is_a($ret, 'PEAR_Error')) {
2899 $x = new DB_DataObject_Generator;
2900 return $x->$proxyMethod( $d->_database, $table);
2903 if (!$rclass || !class_exists($rclass)) {
2904 $dor = new DB_DataObject();
2905 return $dor->raiseError(
2906 "factory could not find class " .
2907 (is_array($class) ? implode(PATH_SEPARATOR, $class) : $class ).
2909 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2912 $ret = new $rclass();
2914 if (!empty($database)) {
2915 DB_DataObject::debug("Setting database to $database","FACTORY",1);
2916 $ret->database($database);
2923 * @param string|array $class Class
2924 * @param string $table Table trying to load.
2926 * @return string classname on Success
2928 function _autoloadClass($class, $table=false)
2930 global $_DB_DATAOBJECT;
2932 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2933 DB_DataObject::_loadConfig();
2935 $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2936 '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
2938 $table = $table ? $table : substr($class,strlen($class_prefix));
2940 // only include the file if it exists - and barf badly if it has parse errors :)
2941 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
2945 // class_location = mydir/ => maps to mydir/Tablename.php
2946 // class_location = mydir/myfile_%s.php => maps to mydir/myfile_Tablename
2947 // with directory sepr
2948 // class_location = mydir/:mydir2/: => tries all of thes locations.
2949 $cl = $_DB_DATAOBJECT['CONFIG']['class_location'];
2953 case (strpos($cl ,'%s') !== false):
2954 $file = sprintf($cl , preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
2957 case (strpos($cl , PATH_SEPARATOR) !== false):
2959 foreach(explode(PATH_SEPARATOR, $cl ) as $p) {
2960 $file[] = $p .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2964 $file = $cl .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2968 $cls = is_array($class) ? $class : array($class);
2970 if (is_array($file) || !file_exists($file)) {
2973 $file = is_array($file) ? $file : array($file);
2974 $search = implode(PATH_SEPARATOR, $file);
2975 foreach($file as $f) {
2976 foreach(explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
2977 $ff = empty($p) ? $f : "$p/$f";
2979 if (file_exists($ff)) {
2990 $dor = new DB_DataObject();
2992 "autoload:Could not find class " . implode(',', $cls) .
2993 " using class_location value :" . $search .
2994 " using include_path value :" . ini_get('include_path'),
2995 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3004 foreach($cls as $c) {
3005 $ce = substr(phpversion(),0,1) > 4 ? class_exists($c,false) : class_exists($c);
3012 $dor = new DB_DataObject();
3014 "autoload:Could not autoload " . implode(',', $cls) ,
3015 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3024 * Have the links been loaded?
3025 * if they have it contains a array of those variables.
3028 * @var boolean | array
3030 var $_link_loaded = false;
3033 * Get the links associate array as defined by the links.ini file.
3037 * Should look a bit like
3038 * [local_col_name] => "related_tablename:related_col_name"
3040 * @param array $new_links optional - force update of the links for this table
3041 * You probably want to restore it to it's original state after,
3042 * as modifying here does it for the whole PHP request.
3044 * @return array|null
3045 * array = if there are links defined for this table.
3046 * empty array - if there is a links.ini file, but no links on this table
3047 * false - if no links.ini exists for this database (hence try auto_links).
3049 * @see DB_DataObject::getLinks(), DB_DataObject::getLink()
3054 global $_DB_DATAOBJECT;
3055 if (empty($_DB_DATAOBJECT['CONFIG'])) {
3056 $this->_loadConfig();
3058 // have to connect.. -> otherwise things break later.
3061 // alias for shorter code..
3062 $lcfg = &$_DB_DATAOBJECT['LINKS'];
3063 $cfg = $_DB_DATAOBJECT['CONFIG'];
3065 if ($args = func_get_args()) {
3066 // an associative array was specified, that updates the current
3067 // schema... - be careful doing this
3068 if (empty( $lcfg[$this->_database])) {
3069 $lcfg[$this->_database] = array();
3071 $lcfg[$this->_database][$this->tableName()] = $args[0];
3074 // loaded and available.
3075 if (isset($lcfg[$this->_database][$this->tableName()])) {
3076 return $lcfg[$this->_database][$this->tableName()];
3080 if (isset($lcfg[$this->_database])) {
3081 // either no file, or empty..
3082 return $lcfg[$this->_database] === false ? null : array();
3085 // links are same place as schema by default.
3086 $schemas = isset($cfg['schema_location']) ?
3087 array("{$cfg['schema_location']}/{$this->_database}.ini") :
3090 // if ini_* is set look there instead.
3091 // and support multiple locations.
3092 if (isset($cfg["ini_{$this->_database}"])) {
3093 $schemas = is_array($cfg["ini_{$this->_database}"]) ?
3094 $cfg["ini_{$this->_database}"] :
3095 explode(PATH_SEPARATOR,$cfg["ini_{$this->_database}"]);
3098 // default to not available.
3099 $lcfg[$this->_database] = false;
3101 foreach ($schemas as $ini) {
3103 $links = isset($cfg["links_{$this->_database}"]) ?
3104 $cfg["links_{$this->_database}"] :
3105 str_replace('.ini','.links.ini',$ini);
3107 // file really exists..
3108 if (!file_exists($links) || !is_file($links)) {
3109 if (!empty($cfg['debug'])) {
3110 $this->debug("Missing links.ini file: $links","links",1);
3115 // set to empty array - as we have at least one file now..
3116 $lcfg[$this->_database] = empty($lcfg[$this->_database]) ? array() : $lcfg[$this->_database];
3118 // merge schema file into lcfg..
3119 $lcfg[$this->_database] = array_merge(
3120 $lcfg[$this->_database],
3121 parse_ini_file($links, true)
3125 if (!empty($cfg['debug'])) {
3126 $this->debug("Loaded links.ini file: $links","links",1);
3131 if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
3132 foreach($lcfg[$this->_database] as $k=>$v) {
3134 $nk = strtolower($k);
3135 // results in duplicate cols.. but not a big issue..
3136 $lcfg[$this->_database][$nk] = isset($lcfg[$this->_database][$nk])
3137 ? $lcfg[$this->_database][$nk] : array();
3139 foreach($v as $kk =>$vv) {
3140 //var_Dump($vv);exit;
3141 $vv =explode(':', $vv);
3142 $vv[0] = strtolower($vv[0]);
3143 $lcfg[$this->_database][$nk][$kk] = implode(':', $vv);
3149 //echo '<PRE>';print_r($lcfg);exit;
3151 // if there is no link data at all on the file!
3153 if ($lcfg[$this->_database] === false) {
3157 if (isset($lcfg[$this->_database][$this->tableName()])) {
3158 return $lcfg[$this->_database][$this->tableName()];
3166 * generic getter/setter for links
3168 * This is the new 'recommended' way to get get/set linked objects.
3169 * must be used with links.ini
3173 * $obj = $do->link('company_id');
3174 * $obj = $do->link(array('local_col', 'linktable:linked_col'));
3177 * $do->link('company_id',0);
3178 * $do->link('company_id',$obj);
3179 * $do->link('company_id', array($obj));
3183 * function company() {
3184 * $this->link(array('company_id','company:id'), func_get_args());
3189 * @param mixed $link_spec link specification (normally a string)
3190 * uses similar rules to joinAdd() array argument.
3191 * @param mixed $set_value (optional) int, DataObject, or array('set')
3192 * @author Alan Knowles
3194 * @return mixed true or false on setting, object on getting
3196 function link($field, $set_args = array())
3198 require_once 'DB/DataObject/Links.php';
3199 $l = new DB_DataObject_Links($this);
3200 return $l->link($field,$set_args) ;
3205 * load related objects
3207 * Generally not recommended to use this.
3208 * The generator should support creating getter_setter methods which are better suited.
3210 * Relies on <dbname>.links.ini
3212 * Sets properties on the calling dataobject you can change what
3213 * object vars the links are stored in by changeing the format parameter
3216 * @param string format (default _%s) where %s is the table name.
3217 * @author Tim White <tim@cyface.com>
3219 * @return boolean , true on success
3221 function getLinks($format = '_%s')
3223 require_once 'DB/DataObject/Links.php';
3224 $l = new DB_DataObject_Links($this);
3225 return $l->applyLinks($format);
3230 * deprecited : @use link()
3232 function getLink($row, $table = null, $link = false)
3234 require_once 'DB/DataObject/Links.php';
3235 $l = new DB_DataObject_Links($this);
3236 return $l->getLink($row, $table === null ? false: $table, $link);
3243 * 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).
3244 * You may also use this with all parameters to specify, the column and related table.
3245 * This is highly dependant on naming columns 'correctly' :)
3246 * using colname = xxxxx_yyyyyy
3247 * xxxxxx = related table; (yyyyy = user defined..)
3248 * looks up table xxxxx, for value id=$this->xxxxx
3249 * stores it in $this->_xxxxx_yyyyy
3252 * @param string $column - either column or column.xxxxx
3253 * @param string $table - name of table to look up value in
3254 * @return array - array of results (empty array on failure)
3256 * Example - Getting the related objects
3258 * $person = new DataObjects_Person;
3260 * $children = $person->getLinkArray('children');
3262 * echo 'There are ', count($children), ' descendant(s):<br />';
3263 * foreach ($children as $child) {
3264 * echo $child->name, '<br />';
3268 function getLinkArray($row, $table = null)
3270 require_once 'DB/DataObject/Links.php';
3271 $l = new DB_DataObject_Links($this);
3272 return $l->getLinkArray($row, $table === null ? false: $table);
3277 * unionAdd - adds another dataobject to this, building a unioned query.
3280 * $doTable1 = DB_DataObject::factory("table1");
3281 * $doTable2 = DB_DataObject::factory("table2");
3283 * $doTable1->selectAdd();
3284 * $doTable1->selectAdd("col1,col2");
3285 * $doTable1->whereAdd("col1 > 100");
3286 * $doTable1->orderBy("col1");
3288 * $doTable2->selectAdd();
3289 * $doTable2->selectAdd("col1, col2");
3290 * $doTable2->whereAdd("col2 = 'v'");
3292 * $doTable1->unionAdd($doTable2);
3293 * $doTable1->find();
3295 * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
3298 * @param $obj object|false the union object or false to reset
3299 * @param optional $is_all string 'ALL' to do all.
3300 * @returns $obj object|array the added object, or old list if reset.
3303 function unionAdd($obj,$is_all= '')
3305 if ($obj === false) {
3306 $ret = $this->_query['unions'];
3307 $this->_query['unions'] = array();
3310 $this->_query['unions'][] = array($obj, 'UNION ' . $is_all . ' ') ;
3317 * The JOIN condition
3325 * joinAdd - adds another dataobject to this, building a joined query.
3327 * example (requires links.ini to be set up correctly)
3328 * // get all the images for product 24
3329 * $i = new DataObject_Image();
3330 * $pi = new DataObjects_Product_image();
3331 * $pi->product_id = 24; // set the product id to 24
3332 * $i->joinAdd($pi); // add the product_image connectoin
3334 * while ($i->fetch()) {
3337 * // an example with 2 joins
3338 * // get all the images linked with products or productgroups
3339 * $i = new DataObject_Image();
3340 * $pi = new DataObject_Product_image();
3341 * $pgi = new DataObject_Productgroup_image();
3343 * $i->joinAdd($pgi);
3345 * while ($i->fetch()) {
3350 * @param optional $obj object |array the joining object (no value resets the join)
3351 * If you use an array here it should be in the format:
3352 * array('local_column','remotetable:remote_column');
3353 * if remotetable does not have a definition, you should
3354 * use @ to hide the include error message..
3355 * array('local_column', $dataobject , 'remote_column');
3356 * if array has 3 args, then second is assumed to be the linked dataobject.
3358 * @param optional $joinType string | array
3359 * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
3360 * just select ... from a,b,c with no join and
3361 * links are added as where items.
3363 * If second Argument is array, it is assumed to be an associative
3364 * array with arguments matching below = eg.
3365 * 'joinType' => 'INNER',
3368 * 'useWhereAsOn' => false,
3370 * @param optional $joinAs string if you want to select the table as anther name
3371 * useful when you want to select multiple columsn
3372 * from a secondary table.
3374 * @param optional $joinCol string The column on This objects table to match (needed
3375 * if this table links to the child object in
3376 * multiple places eg.
3377 * user->friend (is a link to another user)
3378 * user->mother (is a link to another user..)
3380 * optional 'useWhereAsOn' bool default false;
3381 * convert the where argments from the object being added
3382 * into ON arguments.
3387 * @author Stijn de Reede <sjr@gmx.co.uk>
3389 function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
3391 global $_DB_DATAOBJECT;
3392 if ($obj === false) {
3397 //echo '<PRE>'; print_r(func_get_args());
3398 $useWhereAsOn = false;
3399 // support for 2nd argument as an array of options
3400 if (is_array($joinType)) {
3401 // new options can now go in here... (dont forget to document them)
3402 $useWhereAsOn = !empty($joinType['useWhereAsOn']);
3403 $joinCol = isset($joinType['joinCol']) ? $joinType['joinCol'] : $joinCol;
3404 $joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
3405 $joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
3407 // support for array as first argument
3408 // this assumes that you dont have a links.ini for the specified table.
3409 // and it doesnt exist as am extended dataobject!! - experimental.
3411 $ofield = false; // object field
3412 $tfield = false; // this field
3414 if (is_array($obj)) {
3417 if (count($obj) == 3) {
3421 list($toTable,$ofield) = explode(':',$obj[1]);
3423 $obj = is_string($toTable) ? DB_DataObject::factory($toTable) : $toTable;
3425 if (!$obj || !is_object($obj) || is_a($obj,'PEAR_Error')) {
3426 $obj = new DB_DataObject;
3427 $obj->__table = $toTable;
3431 // set the table items to nothing.. - eg. do not try and match
3432 // things in the child table...???
3436 if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
3437 return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
3439 /* make sure $this->_database is set. */
3441 $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3444 /// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
3446 /* otherwise see if there are any links from this table to the obj. */
3447 //print_r($this->links());
3448 if (($ofield === false) && ($links = $this->links())) {
3449 // this enables for support for arrays of links in ini file.
3450 // link contains this_column[] = linked_table:linked_column
3452 // link contains this_column = linked_table:linked_column
3453 foreach ($links as $k => $linkVar) {
3455 if (!is_array($linkVar)) {
3456 $linkVar = array($linkVar);
3458 foreach($linkVar as $v) {
3462 /* link contains {this column} = {linked table}:{linked column} */
3463 $ar = explode(':', $v);
3464 // Feature Request #4266 - Allow joins with multiple keys
3465 if (strpos($k, ',') !== false) {
3466 $k = explode(',', $k);
3468 if (strpos($ar[1], ',') !== false) {
3469 $ar[1] = explode(',', $ar[1]);
3472 if ($ar[0] != $obj->tableName()) {
3475 if ($joinCol !== false) {
3476 if ($k == $joinCol) {
3492 /* look up the links for obj table */
3493 //print_r($obj->links());
3494 if (!$ofield && ($olinks = $obj->links())) {
3496 foreach ($olinks as $k => $linkVar) {
3497 /* link contains {this column} = array ( {linked table}:{linked column} )*/
3498 if (!is_array($linkVar)) {
3499 $linkVar = array($linkVar);
3501 foreach($linkVar as $v) {
3503 /* link contains {this column} = {linked table}:{linked column} */
3504 $ar = explode(':', $v);
3506 // Feature Request #4266 - Allow joins with multiple keys
3507 $links_key_array = strpos($k,',');
3508 if ($links_key_array !== false) {
3509 $k = explode(',', $k);
3512 $ar_array = strpos($ar[1],',');
3513 if ($ar_array !== false) {
3514 $ar[1] = explode(',', $ar[1]);
3517 if ($ar[0] != $this->tableName()) {
3521 // you have explictly specified the column
3522 // and the col is listed here..
3523 // not sure if 1:1 table could cause probs here..
3525 if ($joinCol !== false) {
3527 "joinAdd: You cannot target a join column in the " .
3528 "'link from' table ({$obj->tableName()}). " .
3529 "Either remove the fourth argument to joinAdd() ".
3530 "({$joinCol}), or alter your links.ini file.",
3531 DB_DATAOBJECT_ERROR_NODATA);
3543 // finally if these two table have column names that match do a join by default on them
3545 if (($ofield === false) && $joinCol) {
3550 /* did I find a conneciton between them? */
3552 if ($ofield === false) {
3554 "joinAdd: {$obj->tableName()} has no link with {$this->tableName()}",
3555 DB_DATAOBJECT_ERROR_NODATA);
3558 $joinType = strtoupper($joinType);
3560 // we default to joining as the same name (this is remvoed later..)
3562 if ($joinAs === false) {
3563 $joinAs = $obj->tableName();
3566 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
3567 $options = $_DB_DATAOBJECT['CONFIG'];
3569 // not sure how portable adding database prefixes is..
3570 $objTable = $quoteIdentifiers ?
3571 $DB->quoteIdentifier($obj->tableName()) :
3575 if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
3576 $dbPrefix = ($quoteIdentifiers
3577 ? $DB->quoteIdentifier($obj->_database)
3578 : $obj->_database) . '.';
3581 // if they are the same, then dont add a prefix...
3582 if ($obj->_database == $this->_database) {
3585 // as far as we know only mysql supports database prefixes..
3586 // prefixing the database name is now the default behaviour,
3587 // as it enables joining mutiple columns from multiple databases...
3589 // prefix database (quoted if neccessary..)
3590 $objTable = $dbPrefix . $objTable;
3594 // if obj only a dataobject - eg. no extended class has been defined..
3595 // it obvioulsy cant work out what child elements might exist...
3596 // until we get on the fly querying of tables..
3597 // note: we have already checked that it is_a(db_dataobject earlier)
3598 if ( strtolower(get_class($obj)) != 'db_dataobject') {
3600 // now add where conditions for anything that is set in the object
3604 $items = $obj->table();
3605 // will return an array if no items..
3607 // only fail if we where expecting it to work (eg. not joined on a array)
3611 "joinAdd: No table definition for {$obj->tableName()}",
3612 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3616 $ignore_null = !isset($options['disable_null_strings'])
3617 || !is_string($options['disable_null_strings'])
3618 || strtolower($options['disable_null_strings']) !== 'full' ;
3621 foreach($items as $k => $v) {
3622 if (!isset($obj->$k) && $ignore_null) {
3626 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
3628 if (DB_DataObject::_is_null($obj,$k)) {
3629 $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
3633 if ($v & DB_DATAOBJECT_STR) {
3634 $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
3635 ($v & DB_DATAOBJECT_BOOL) ?
3636 // this is thanks to the braindead idea of postgres to
3637 // use t/f for boolean.
3638 (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
3643 if (is_numeric($obj->$k)) {
3644 $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
3648 if (is_object($obj->$k) && is_a($obj->$k,'DB_DataObject_Cast')) {
3649 $value = $obj->$k->toString($v,$DB);
3650 if (PEAR::isError($value)) {
3651 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
3654 $obj->whereAdd("{$joinAs}.{$kSql} = $value");
3659 /* this is probably an error condition! */
3660 $obj->whereAdd("{$joinAs}.{$kSql} = 0");
3662 if ($this->_query === false) {
3664 "joinAdd can not be run from a object that has had a query run on it,
3665 clone the object or create a new one and use setFrom()",
3666 DB_DATAOBJECT_ERROR_INVALIDARGS);
3671 // and finally merge the whereAdd from the child..
3672 if ($obj->_query['condition']) {
3673 $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
3675 if (!$useWhereAsOn) {
3676 $this->whereAdd($cond);
3683 // nested (join of joined objects..)
3686 // postgres allows nested queries, with ()'s
3687 // not sure what the results are with other databases..
3688 // may be unpredictable..
3689 if (in_array($DB->dsn["phptype"],array('pgsql'))) {
3690 $objTable = "($objTable {$obj->_join})";
3692 $appendJoin = $obj->_join;
3698 // add the joinee object's conditions to the ON clause instead of the WHERE clause
3699 if ($useWhereAsOn && strlen($cond)) {
3700 $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
3705 $table = $this->tableName();
3707 if ($quoteIdentifiers) {
3708 $joinAs = $DB->quoteIdentifier($joinAs);
3709 $table = $DB->quoteIdentifier($table);
3710 $ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
3711 $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
3713 // add database prefix if they are different databases
3717 $addJoinAs = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->tableName()) : $obj->tableName()) != $joinAs;
3719 // join table a AS b - is only supported by a few databases and is probably not needed
3720 // , however since it makes the whole Statement alot clearer we are leaving it in
3721 // for those databases.
3722 $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
3725 $joinAs = $dbPrefix . $joinAs;
3729 switch ($joinType) {
3732 case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
3734 // Feature Request #4266 - Allow joins with multiple keys
3735 $jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3736 //$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3737 if (is_array($ofield)) {
3738 $key_count = count($ofield);
3739 for($i = 0; $i < $key_count; $i++) {
3741 $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
3744 $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
3747 $jadd .= ' ' . $appendJoin . ' ';
3749 $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
3751 // jadd avaliable for debugging join build.
3753 $this->_join .= $jadd;
3756 case '': // this is just a standard multitable select..
3757 $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
3758 $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
3767 * autoJoin - using the links.ini file, it builds a query with all the joins
3769 * $x = DB_DataObject::factory('mytable');
3772 * will result in all of the joined data being added to the fetched object..
3774 * $x = DB_DataObject::factory('mytable');
3776 * $ar = $x->fetchAll();
3777 * will result in an array containing all the data from the table, and any joined tables..
3779 * $x = DB_DataObject::factory('mytable');
3780 * $jdata = $x->autoJoin();
3781 * $x->selectAdd(); //reset..
3782 * foreach($_REQUEST['requested_cols'] as $c) {
3783 * if (!isset($jdata[$c])) continue; // ignore columns not available..
3784 * $x->selectAdd( $jdata[$c] . ' as ' . $c);
3786 * $ar = $x->fetchAll();
3787 * will result in only the columns requested being fetched...
3791 * @param array Configuration
3792 * exclude Array of columns to exclude from results (eg. modified_by_id)
3793 * links The equivilant links.ini data for this table eg.
3794 * array( 'person_id' => 'person:id', .... )
3795 * include Array of columns to include
3796 * distinct Array of distinct columns.
3798 * @return array info about joins
3799 * cols => map of resulting {joined_tablename}.{joined_table_column_name}
3800 * join_names => map of resulting {join_name_as}.{joined_table_column_name}
3801 * count => the column to count on.
3804 function autoJoin($cfg = array())
3806 global $_DB_DATAOBJECT;
3807 //var_Dump($cfg);exit;
3808 $pre_links = $this->links();
3809 if (!empty($cfg['links'])) {
3810 $this->links(array_merge( $pre_links , $cfg['links']));
3812 $map = $this->links( );
3814 $this->databaseStructure();
3815 $dbstructure = $_DB_DATAOBJECT['INI'][$this->_database];
3817 $tabdef = $this->table();
3819 // we need this as normally it's only cleared by an empty selectAs call.
3822 $keys = array_keys($tabdef);
3823 if (!empty($cfg['exclude'])) {
3824 $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
3826 if (!empty($cfg['include'])) {
3828 $keys = array_intersect($keys, $cfg['include']);
3831 $selectAs = array();
3833 if (!empty($keys)) {
3834 $selectAs = array(array( $keys , '%s', false));
3839 'join_names' => array(),
3845 $has_distinct = false;
3846 if (!empty($cfg['distinct']) && $keys) {
3848 // reset the columsn?
3851 //echo '<PRE>' ;print_r($xx);exit;
3852 foreach($keys as $c) {
3855 if ( $cfg['distinct'] == $c) {
3856 $has_distinct = 'DISTINCT( ' . $this->tableName() .'.'. $c .') as ' . $c;
3857 $ret['count'] = 'DISTINCT ' . $this->tableName() .'.'. $c .'';
3860 // cols is in our filtered keys...
3864 // apply our filtered version, which excludes the distinct column.
3866 $selectAs = empty($cols) ? array() : array(array(array( $cols) , '%s', false)) ;
3872 foreach($keys as $k) {
3873 $ret['cols'][$k] = $this->tableName(). '.' . $k;
3878 foreach($map as $ocl=>$info) {
3880 list($tab,$col) = explode(':', $info);
3881 // what about multiple joins on the same table!!!
3883 // if links point to a table that does not exist - ignore.
3884 if (!isset($dbstructure[$tab])) {
3888 $xx = DB_DataObject::factory($tab);
3889 if (!is_object($xx) || !is_a($xx, 'DB_DataObject')) {
3892 // skip columns that are excluded.
3894 // we ignore include here... - as
3896 // this is borked ... for multiple jions..
3897 $this->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
3899 if (!empty($cfg['exclude']) && in_array($ocl, $cfg['exclude'])) {
3903 $tabdef = $xx->table();
3904 $table = $xx->tableName();
3906 $keys = array_keys($tabdef);
3909 if (!empty($cfg['exclude'])) {
3910 $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
3912 foreach($keys as $k) {
3913 if (in_array($ocl.'_'.$k, $cfg['exclude'])) {
3914 $keys = array_diff($keys, $k); // removes the k..
3920 if (!empty($cfg['include'])) {
3921 // include will basically be BASECOLNAME_joinedcolname
3923 foreach($keys as $k) {
3924 if (in_array( sprintf($ocl.'_%s', $k), $cfg['include'])) {
3934 // got distinct, and not yet found it..
3935 if (!$has_distinct && !empty($cfg['distinct'])) {
3937 foreach($keys as $c) {
3938 $tn = sprintf($ocl.'_%s', $c);
3940 if ( $tn == $cfg['distinct']) {
3942 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$c .') as ' . $tn ;
3943 $ret['count'] = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$c;
3944 // var_dump($this->countWhat );
3951 if (!empty($cols)) {
3952 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
3956 $selectAs[] = array($keys, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
3959 foreach($keys as $k) {
3960 $ret['cols'][sprintf('%s_%s', $ocl, $k)] = $tab.'.'.$k;
3961 $ret['join_names'][sprintf('%s_%s', $ocl, $k)] = sprintf('join_%s_%s.%s',$ocl, $col, $k);
3966 // fill in the select details..
3969 if ($has_distinct) {
3970 $this->selectAdd($has_distinct);
3973 foreach($selectAs as $ar) {
3974 $this->selectAs($ar[0], $ar[1], $ar[2]);
3977 $this->links( $pre_links );
3984 * Factory method for calling DB_DataObject_Cast
3986 * if used with 1 argument DB_DataObject_Cast::sql($value) is called
3988 * if used with 2 arguments DB_DataObject_Cast::$value($callvalue) is called
3989 * valid first arguments are: blob, string, date, sql
3991 * eg. $member->updated = $member->sqlValue('NOW()');
3994 * might handle more arguments for escaping later...
3997 * @param string $value (or type if used with 2 arguments)
3998 * @param string $callvalue (optional) used with date/null etc..
4001 function sqlValue($value)
4004 if (func_num_args() == 2) {
4006 $value = func_get_arg(1);
4008 require_once 'DB/DataObject/Cast.php';
4009 return call_user_func(array('DB_DataObject_Cast', $method), $value);
4015 * Copies items that are in the table definitions from an
4016 * array or object into the current object
4017 * will not override key values.
4020 * @param array | object $from
4021 * @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
4022 * @param boolean $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
4024 * @return true on success or array of key=>setValue error message
4026 function setFrom($from, $format = '%s', $skipEmpty=false)
4028 global $_DB_DATAOBJECT;
4029 $keys = $this->keys();
4030 $items = $this->table();
4034 "setFrom:Could not find table definition for {$this->tableName()}",
4035 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
4038 $overload_return = array();
4039 foreach (array_keys($items) as $k) {
4040 if (in_array($k,$keys)) {
4041 continue; // dont overwrite keys
4044 continue; // ignore empty keys!!! what
4047 $chk = is_object($from) &&
4048 (version_compare(phpversion(), "5.1.0" , ">=") ?
4049 property_exists($from, sprintf($format,$k)) : // php5.1
4050 array_key_exists( sprintf($format,$k), get_class_vars($from)) //older
4052 // if from has property ($format($k)
4054 $kk = (strtolower($k) == 'from') ? '_from' : $k;
4055 if (method_exists($this,'set'.$kk)) {
4056 $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
4057 if (is_string($ret)) {
4058 $overload_return[$k] = $ret;
4062 $this->$k = $from->{sprintf($format,$k)};
4066 if (is_object($from)) {
4070 if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
4074 if (!isset($from[sprintf($format,$k)]) && !DB_DataObject::_is_null($from, sprintf($format,$k))) {
4078 $kk = (strtolower($k) == 'from') ? '_from' : $k;
4079 if (method_exists($this,'set'. $kk)) {
4080 $ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
4081 if (is_string($ret)) {
4082 $overload_return[$k] = $ret;
4086 $val = $from[sprintf($format,$k)];
4087 if (is_a($val, 'DB_DataObject_Cast')) {
4091 if (is_object($val) || is_array($val)) {
4094 $ret = $this->fromValue($k,$val);
4095 if ($ret !== true) {
4096 $overload_return[$k] = 'Not A Valid Value';
4098 //$this->$k = $from[sprintf($format,$k)];
4100 if ($overload_return) {
4101 return $overload_return;
4107 * Returns an associative array from the current data
4108 * (kind of oblivates the idea behind DataObjects, but
4109 * is usefull if you use it with things like QuickForms.
4111 * you can use the format to return things like user[key]
4112 * by sending it $object->toArray('user[%s]')
4114 * will also return links converted to arrays.
4116 * @param string sprintf format for array
4117 * @param bool||number [true = elemnts that have a value set],
4118 * [false = table + returned colums] ,
4119 * [0 = returned columsn only]
4122 * @return array of key => value for row
4125 function toArray($format = '%s', $hideEmpty = false)
4127 global $_DB_DATAOBJECT;
4129 // we use false to ignore sprintf.. (speed up..)
4130 $format = $format == '%s' ? false : $format;
4133 $rf = ($this->_resultFields !== false) ? $this->_resultFields :
4134 (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ?
4135 $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
4137 $ar = ($rf !== false) ?
4138 (($hideEmpty === 0) ? $rf : array_merge($rf, $this->table())) :
4141 foreach($ar as $k=>$v) {
4143 if (!isset($this->$k)) {
4145 $ret[$format === false ? $k : sprintf($format,$k)] = '';
4149 // call the overloaded getXXXX() method. - except getLink and getLinks
4150 if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
4151 $ret[$format === false ? $k : sprintf($format,$k)] = $this->{'get'.$k}();
4154 // should this call toValue() ???
4155 $ret[$format === false ? $k : sprintf($format,$k)] = $this->$k;
4157 if (!$this->_link_loaded) {
4160 foreach($this->_link_loaded as $k) {
4161 $ret[$format === false ? $k : sprintf($format,$k)] = $this->$k->toArray();
4169 * validate the values of the object (usually prior to inserting/updating..)
4171 * Note: This was always intended as a simple validation routine.
4172 * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
4174 * This should be moved to another class: DB_DataObject_Validate
4175 * FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
4178 * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
4181 * - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
4182 * - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
4183 * These methods should return
4184 * true = everything ok
4185 * false|object = something is wrong!
4187 * - This method loads and uses the PEAR Validate Class.
4191 * @return array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
4195 global $_DB_DATAOBJECT;
4196 require_once 'Validate.php';
4197 $table = $this->table();
4199 $seq = $this->sequenceKey();
4200 $options = $_DB_DATAOBJECT['CONFIG'];
4201 foreach($table as $key => $val) {
4204 // call user defined validation always...
4205 $method = "Validate" . ucfirst($key);
4206 if (method_exists($this, $method)) {
4207 $ret[$key] = $this->$method();
4211 // if not null - and it's not set.......
4213 if ($val & DB_DATAOBJECT_NOTNULL && DB_DataObject::_is_null($this, $key)) {
4214 // dont check empty sequence key values..
4215 if (($key == $seq[0]) && ($seq[1] == true)) {
4223 if (DB_DataObject::_is_null($this, $key)) {
4224 if ($val & DB_DATAOBJECT_NOTNULL) {
4225 $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
4232 // ignore things that are not set. ?
4234 if (!isset($this->$key)) {
4238 // if the string is empty.. assume it is ok..
4239 if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
4243 // dont try and validate cast objects - assume they are problably ok..
4244 if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
4247 // at this point if you have set something to an object, and it's not expected
4248 // the Validate will probably break!!... - rightly so! (your design is broken,
4249 // so issuing a runtime error like PEAR_Error is probably not appropriate..
4252 // todo: date time.....
4253 case ($val & DB_DATAOBJECT_STR):
4254 $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
4256 case ($val & DB_DATAOBJECT_INT):
4257 $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
4261 // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
4262 foreach ($ret as $key => $val) {
4263 if ($val !== true) {
4267 return true; // everything is OK.
4271 * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
4274 * @return object The DB connection
4276 function getDatabaseConnection()
4278 global $_DB_DATAOBJECT;
4280 if (($e = $this->_connect()) !== true) {
4283 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4287 return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
4292 * Gets the DB result object related to the objects active query
4293 * - so you can use funky pear stuff with it - like pager for example.. :)
4296 * @return object The DB result object
4299 function getDatabaseResult()
4301 global $_DB_DATAOBJECT;
4303 if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4307 return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
4311 * Overload Extension support
4312 * - enables setCOLNAME/getCOLNAME
4313 * if you define a set/get method for the item it will be called.
4314 * otherwise it will just return/set the value.
4315 * NOTE this currently means that a few Names are NO-NO's
4316 * eg. links,link,linksarray, from, Databaseconnection,databaseresult
4319 * - set is automatically called by setFrom.
4320 * - get is automatically called by toArray()
4322 * setters return true on success. = strings on failure
4323 * getters return the value!
4325 * this fires off trigger_error - if any problems.. pear_error,
4326 * has problems with 4.3.2RC2 here
4334 function _call($method,$params,&$return) {
4336 //$this->debug("ATTEMPTING OVERLOAD? $method");
4337 // ignore constructors : - mm
4338 if (strtolower($method) == strtolower(get_class($this))) {
4341 $type = strtolower(substr($method,0,3));
4342 $class = get_class($this);
4343 if (($type != 'set') && ($type != 'get')) {
4349 // deal with naming conflick of setFrom = this is messy ATM!
4351 if (strtolower($method) == 'set_from') {
4352 $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
4356 $element = substr($method,3);
4358 // dont you just love php's case insensitivity!!!!
4360 $array = array_keys(get_class_vars($class));
4361 /* php5 version which segfaults on 5.0.3 */
4362 if (class_exists('ReflectionClass')) {
4363 $reflection = new ReflectionClass($class);
4364 $array = array_keys($reflection->getdefaultProperties());
4367 if (!in_array($element,$array)) {
4369 foreach($array as $k) {
4370 $case[strtolower($k)] = $k;
4372 if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
4373 trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
4374 $element = strtolower($element);
4377 // does it really exist?
4378 if (!isset($case[$element])) {
4381 // use the mundged case
4382 $element = $case[$element]; // real case !
4386 if ($type == 'get') {
4387 $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
4392 $return = $this->fromValue($element, $params[0]);
4401 * standard set* implementation.
4403 * takes data and uses it to set dates/strings etc.
4404 * normally called from __call..
4407 * date = using (standard time format, or unixtimestamp).... so you could create a method :
4408 * function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
4410 * time = using strtotime
4411 * datetime = using same as date - accepts iso standard or unixtimestamp.
4412 * string = typecast only..
4414 * TODO: add formater:: eg. d/m/Y for date! ???
4416 * @param string column of database
4417 * @param mixed value to assign
4419 * @return true| false (False on error)
4421 * @see DB_DataObject::_call
4425 function fromValue($col,$value)
4427 global $_DB_DATAOBJECT;
4428 $options = $_DB_DATAOBJECT['CONFIG'];
4429 $cols = $this->table();
4430 // dont know anything about this col..
4431 if (!isset($cols[$col]) || is_a($value, 'DB_DataObject_Cast')) {
4432 $this->$col = $value;
4435 //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
4437 // set to null and column is can be null...
4438 case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
4439 case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
4440 $this->$col = $value;
4443 // fail on setting null on a not null field..
4444 case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value,false)):
4448 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
4449 // empty values get set to '' (which is inserted/updated as NULl
4454 if (is_numeric($value)) {
4455 $this->$col = date('Y-m-d H:i:s', $value);
4459 // eak... - no way to validate date time otherwise...
4460 $this->$col = (string) $value;
4463 case ($cols[$col] & DB_DATAOBJECT_DATE):
4464 // empty values get set to '' (which is inserted/updated as NULl
4471 if (is_numeric($value)) {
4472 $this->$col = date('Y-m-d',$value);
4477 require_once 'Date.php';
4478 $x = new Date($value);
4479 $this->$col = $x->format("%Y-%m-%d");
4482 case ($cols[$col] & DB_DATAOBJECT_TIME):
4483 // empty values get set to '' (which is inserted/updated as NULl
4488 $guess = strtotime($value);
4490 $this->$col = date('H:i:s', $guess);
4491 return $return = true;
4493 // otherwise an error in type...
4496 case ($cols[$col] & DB_DATAOBJECT_STR):
4498 $this->$col = (string) $value;
4501 // todo : floats numerics and ints...
4503 $this->$col = $value;
4511 * standard get* implementation.
4514 * supported formaters:
4515 * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
4516 * numbers : %02d (eg. sprintf)
4517 * NOTE you will get unexpected results with times like 0000-00-00 !!!
4521 * @param string column of database
4522 * @param format foramt
4524 * @return true Description
4526 * @see DB_DataObject::_call(),strftime(),Date::format()
4528 function toValue($col,$format = null)
4530 if (is_null($format)) {
4533 $cols = $this->table();
4535 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
4539 $guess = strtotime($this->$col);
4541 return strftime($format, $guess);
4543 // eak... - no way to validate date time otherwise...
4545 case ($cols[$col] & DB_DATAOBJECT_DATE):
4549 $guess = strtotime($this->$col);
4551 return strftime($format,$guess);
4554 require_once 'Date.php';
4555 $x = new Date($this->$col);
4556 return $x->format($format);
4558 case ($cols[$col] & DB_DATAOBJECT_TIME):
4562 $guess = strtotime($this->$col);
4564 return strftime($format, $guess);
4566 // otherwise an error in type...
4569 case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
4573 require_once 'Date.php';
4575 $x = new Date($this->$col);
4577 return $x->format($format);
4580 case ($cols[$col] & DB_DATAOBJECT_BOOL):
4582 if ($cols[$col] & DB_DATAOBJECT_STR) {
4584 return ($this->$col === 't');
4586 return (bool) $this->$col;
4590 return sprintf($format,$this->col);
4597 /* ----------------------- Debugger ------------------ */
4600 * Debugger. - use this in your extended classes to output debugging information.
4602 * Uses DB_DataObject::DebugLevel(x) to turn it on
4604 * @param string $message - message to output
4605 * @param string $logtype - bold at start
4606 * @param string $level - output level
4610 function debug($message, $logtype = 0, $level = 1)
4612 global $_DB_DATAOBJECT;
4614 if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
4615 (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
4618 // this is a bit flaky due to php's wonderfull class passing around crap..
4619 // but it's about as good as it gets..
4620 $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
4622 if (!is_string($message)) {
4623 $message = print_r($message,true);
4625 if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
4626 return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
4629 if (!ini_get('html_errors')) {
4630 echo "$class : $logtype : $message\n";
4634 if (!is_string($message)) {
4635 $message = print_r($message,true);
4637 $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
4638 echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
4642 * sets and returns debug level
4643 * eg. DB_DataObject::debugLevel(4);
4645 * @param int $v level
4649 static function debugLevel($v = null)
4651 global $_DB_DATAOBJECT;
4652 if (empty($_DB_DATAOBJECT['CONFIG'])) {
4653 DB_DataObject::_loadConfig();
4656 $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4657 $_DB_DATAOBJECT['CONFIG']['debug'] = $v;
4660 return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4664 * Last Error that has occured
4665 * - use $this->_lastError or
4666 * $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
4669 * @var object PEAR_Error (or false)
4671 var $_lastError = false;
4674 * Default error handling is to create a pear error, but never return it.
4675 * if you need to handle errors you should look at setting the PEAR_Error callback
4676 * this is due to the fact it would wreck havoc on the internal methods!
4678 * @param int $message message
4679 * @param int $type type
4680 * @param int $behaviour behaviour (die or continue!);
4682 * @return error object
4684 function raiseError($message, $type = null, $behaviour = null)
4686 global $_DB_DATAOBJECT;
4688 if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
4692 $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4695 // no checks for production here?....... - we log errors before we throw them.
4696 DB_DataObject::debug($message,'ERROR',1);
4699 if (PEAR::isError($message)) {
4702 require_once 'DB/DataObject/Error.php';
4704 $error = $dor->raiseError($message, $type, $behaviour,
4705 $opts=null, $userinfo=null, 'DB_DataObject_Error'
4708 // this will never work totally with PHP's object model.
4709 // as this is passed on static calls (like staticGet in our case)
4711 $_DB_DATAOBJECT['LASTERROR'] = $error;
4713 if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
4714 $this->_lastError = $error;
4721 * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
4723 * After Profiling DB_DataObject, I discoved that the debug calls where taking
4724 * considerable time (well 0.1 ms), so this should stop those calls happening. as
4725 * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
4726 * THIS STILL NEEDS FURTHER INVESTIGATION
4729 * @return object an error object
4731 function _loadConfig()
4733 global $_DB_DATAOBJECT;
4735 $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
4740 * Free global arrays associated with this object.
4748 global $_DB_DATAOBJECT;
4750 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
4751 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
4753 if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4754 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
4756 // clear the staticGet cache as well.
4757 $this->_clear_cache();
4758 // this is a huge bug in DB!
4759 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4760 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
4763 if (is_array($this->_link_loaded)) {
4764 foreach ($this->_link_loaded as $do) {
4766 !empty($this->{$do}) &&
4767 is_object($this->{$do}) &&
4768 method_exists($this->{$do}, 'free')
4770 $this->{$do}->free();
4778 * Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
4779 * If the value is a string set to "null" and the "disable_null_strings" option is not set to
4780 * true, then the value is considered to be null.
4781 * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to
4782 * the value "full", then it will also be considered null. - this can not differenticate between not set
4785 * @param object|array $obj_or_ar
4786 * @param string|false $prop prperty
4789 * @return bool object
4791 function _is_null($obj_or_ar , $prop)
4793 global $_DB_DATAOBJECT;
4796 $isset = $prop === false ? isset($obj_or_ar) :
4797 (is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
4800 ($prop === false ? $obj_or_ar :
4801 (is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
4806 $options = $_DB_DATAOBJECT['CONFIG'];
4808 $null_strings = !isset($options['disable_null_strings'])
4809 || $options['disable_null_strings'] === false;
4811 $crazy_null = isset($options['disable_null_strings'])
4812 && is_string($options['disable_null_strings'])
4813 && strtolower($options['disable_null_strings'] === 'full');
4815 if ( $null_strings && $isset && is_string($value) && (strtolower($value) === 'null') ) {
4819 if ( $crazy_null && !$isset ) {
4829 * (deprecated - use ::get / and your own caching method)
4831 static function staticGet($class, $k, $v = null)
4833 $lclass = strtolower($class);
4834 global $_DB_DATAOBJECT;
4835 if (empty($_DB_DATAOBJECT['CONFIG'])) {
4836 DB_DataObject::_loadConfig();
4845 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
4846 DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
4848 if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
4849 return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
4851 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
4852 DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
4855 $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
4856 if (PEAR::isError($obj)) {
4857 $dor = new DB_DataObject();
4858 $dor->raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
4863 if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
4864 $_DB_DATAOBJECT['CACHE'][$lclass] = array();
4866 if (!$obj->get($k,$v)) {
4867 $dor = new DB_DataObject();
4868 $dor->raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
4873 $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
4874 return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
4878 * autoload Class relating to a table
4879 * (deprecited - use ::factory)
4881 * @param string $table table
4883 * @return string classname on Success
4885 function staticAutoloadTable($table)
4887 global $_DB_DATAOBJECT;
4888 if (empty($_DB_DATAOBJECT['CONFIG'])) {
4889 DB_DataObject::_loadConfig();
4891 $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
4892 $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
4893 $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
4895 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
4896 $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
4900 /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
4902 function _get_table() { return $this->table(); }
4903 function _get_keys() { return $this->keys(); }
4909 // technially 4.3.2RC1 was broken!!
4910 // looks like 4.3.3 may have problems too....
4911 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
4913 if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
4914 if (version_compare( phpversion(), "5") < 0) {
4915 overload('DB_DataObject');
4917 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;