3 * Object Based Database Query Builder and data store
7 * LICENSE: This source file is subject to version 3.0 of the PHP license
8 * that is available through the world-wide-web at the following URI:
9 * http://www.php.net/license/3_0.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_0.txt PHP License 3.0
18 * @version CVS: $Id: DataObject.php,v 1.439 2008/01/30 02:14:06 alan_k Exp $
19 * @link http://pear.php.net/package/DB_DataObject
23 /* ===========================================================================
25 * !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
27 * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
28 * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
29 * this file. reducing the optimization level may also solve the segfault.
30 * ===========================================================================
34 * The main "DB_DataObject" class is really a base class for your own tables classes
36 * // Set up the class by creating an ini file (refer to the manual for more details
38 * database = mysql:/username:password@host/database
39 * schema_location = /home/myapplication/database
40 * class_location = /home/myapplication/DBTables/
41 * clase_prefix = DBTables_
44 * //Start and initialize...................... - dont forget the &
45 * $config = parse_ini_file('example.ini',true);
46 * $options = &PEAR::getStaticProperty('DB_DataObject','options');
47 * $options = $config['DB_DataObject'];
49 * // example of a class (that does not use the 'auto generated tables data')
50 * class mytable extends DB_DataObject {
51 * // mandatory - set the table
52 * var $_database_dsn = "mysql://username:password@localhost/database";
53 * var $__table = "mytable";
56 * 'id' => 1, // integer or number
57 * 'name' => 2, // string
65 * // use in the application
70 * $instance = new mytable;
71 * $instance->get("id",12);
72 * echo $instance->somedata;
77 * $instance = new mytable;
78 * $instance->whereAdd("ID > 12");
79 * $instance->whereAdd("ID < 14");
81 * while ($instance->fetch()) {
82 * echo $instance->somedata;
88 * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
91 require_once 'PEAR.php';
94 * We are duping fetchmode constants to be compatible with
97 define('DB_DATAOBJECT_FETCHMODE_ORDERED',1);
98 define('DB_DATAOBJECT_FETCHMODE_ASSOC',2);
105 * these are constants for the get_table array
106 * user to determine what type of escaping is required around the object vars.
108 define('DB_DATAOBJECT_INT', 1); // does not require ''
109 define('DB_DATAOBJECT_STR', 2); // requires ''
111 define('DB_DATAOBJECT_DATE', 4); // is date #TODO
112 define('DB_DATAOBJECT_TIME', 8); // is time #TODO
113 define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
114 define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
115 define('DB_DATAOBJECT_BLOB', 64); // is blob type
118 define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
119 define('DB_DATAOBJECT_MYSQLTIMESTAMP' , 256); // mysql timestamps (ignored by update/insert)
121 * Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
123 //define('DB_DATAOBJECT_NO_OVERLOAD',true)
127 * Theses are the standard error codes, most methods will fail silently - and return false
128 * to access the error message either use $table->_lastError
129 * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
130 * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
133 define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
134 define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
135 define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
136 define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
137 define('DB_DATAOBJECT_ERROR_INVALID_CALL' ,-7); // overlad getter/setter failure
140 * Used in methods like delete() and count() to specify that the method should
141 * build the condition only out of the whereAdd's and not the object parameters.
143 define('DB_DATAOBJECT_WHEREADD_ONLY', true);
147 * storage for connection and result objects,
148 * it is done this way so that print_r()'ing the is smaller, and
149 * it reduces the memory size of the object.
150 * -- future versions may use $this->_connection = & PEAR object..
151 * although will need speed tests to see how this affects it.
152 * - includes sub arrays
153 * - connections = md5 sum mapp to pear db object
154 * - results = [id] => map to pear db object
155 * - resultseq = sequence id for results & results field
156 * - resultfields = [id] => list of fields return from query (for use with toArray())
157 * - ini = mapping of database to ini file results
158 * - links = mapping of database to links file
159 * - lasterror = pear error objects for last error event.
160 * - config = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
161 * - array of loaded classes by autoload method - to stop it doing file access request over and over again!
163 $GLOBALS['_DB_DATAOBJECT']['RESULTS'] = array();
164 $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
165 $GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
166 $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
167 $GLOBALS['_DB_DATAOBJECT']['INI'] = array();
168 $GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
169 $GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
170 $GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
171 $GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
172 $GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
173 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
174 $GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
178 // this will be horrifically slow!!!!
179 // NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer (see define before..)
180 // these two are BC/FC handlers for call in PHP4/5
182 if ( substr(phpversion(),0,1) == 5) {
183 class DB_DataObject_Overload
185 function __call($method,$args)
188 $this->_call($method,$args,$return);
193 return array_keys(get_object_vars($this)) ;
197 if (version_compare(phpversion(),'4.3.10','eq') && !defined('DB_DATAOBJECT_NO_OVERLOAD')) {
199 "overload does not work with PHP4.3.10, either upgrade
200 (snaps.php.net) or more recent version
201 or define DB_DATAOBJECT_NO_OVERLOAD as per the manual.
205 if (!function_exists('clone')) {
206 // emulate clone - as per php_compact, slow but really the correct behaviour..
207 eval('function clone($t) { $r = $t; if (method_exists($r,"__clone")) { $r->__clone(); } return $r; }');
210 class DB_DataObject_Overload {
211 function __call($method,$args,&$return) {
212 return $this->_call($method,$args,$return);
225 * @package DB_DataObject
226 * @author Alan Knowles <alan@akbkhome.com>
230 class DB_DataObject extends DB_DataObject_Overload
233 * The Version - use this to check feature changes
238 var $_DB_DataObject_version = "1.8.8";
241 * The Database table (used by table extends)
246 var $__table = ''; // database table
249 * The Number of rows returned from a query
254 var $N = 0; // Number of rows returned from a query
256 /* ============================================================= */
257 /* Major Public Methods */
258 /* (designed to be optionally then called with parent::method()) */
259 /* ============================================================= */
263 * Get a result using key, value.
266 * $object->get("ID",1234);
267 * Returns Number of rows located (usually 1) for success,
268 * and puts all the table columns into this classes variables
270 * see the fetch example on how to extend this.
272 * if no value is entered, it is assumed that $key is a value
273 * and get will then use the first key in keys()
276 * @param string $k column
277 * @param string $v value
279 * @return int No. of rows
281 function get($k = null, $v = null)
283 global $_DB_DATAOBJECT;
284 if (empty($_DB_DATAOBJECT['CONFIG'])) {
285 DB_DataObject::_loadConfig();
291 $keys = $this->keys();
293 $this->raiseError("No Keys available for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
298 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
299 $this->debug("$k $v " .print_r($keys,true), "GET");
303 $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
307 return $this->find(1);
311 * An autoloading, caching static get method using key, value (based on get)
314 * $object = DB_DataObject::staticGet("DbTable_mytable",12);
316 * $object = DB_DataObject::staticGet("DbTable_mytable","name","fred");
318 * or write it into your extended class:
319 * function &staticGet($k,$v=NULL) { return DB_DataObject::staticGet("This_Class",$k,$v); }
321 * @param string $class class name
322 * @param string $k column (or value if using keys)
323 * @param string $v value (optional)
327 function &staticGet($class, $k, $v = null)
329 $lclass = strtolower($class);
330 global $_DB_DATAOBJECT;
331 if (empty($_DB_DATAOBJECT['CONFIG'])) {
332 DB_DataObject::_loadConfig();
341 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
342 DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
344 if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
345 return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
347 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
348 DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
351 $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
352 if (PEAR::isError($obj)) {
353 DB_DataObject::raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
358 if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
359 $_DB_DATAOBJECT['CACHE'][$lclass] = array();
361 if (!$obj->get($k,$v)) {
362 DB_DataObject::raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
367 $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
368 return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
372 * find results, either normal or crosstable
376 * $object = new mytable();
381 * will set $object->N to number of rows, and expects next command to fetch rows
382 * will return $object->N
384 * @param boolean $n Fetch first result
386 * @return mixed (number of rows returned, or true if numRows fetching is not supported)
388 function find($n = false)
390 global $_DB_DATAOBJECT;
391 if ($this->_query === false) {
393 "You cannot do two queries on the same object (copy it before finding)",
394 DB_DATAOBJECT_ERROR_INVALIDARGS);
398 if (empty($_DB_DATAOBJECT['CONFIG'])) {
399 DB_DataObject::_loadConfig();
402 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
403 $this->debug($n, "find",1);
405 if (!$this->__table) {
406 // xdebug can backtrace this!
407 trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
410 $query_before = $this->_query;
411 $this->_build_condition($this->table()) ;
413 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
415 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
417 /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
419 $this->_query['data_select'] . " \n" .
420 ' FROM ' . ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table) . " \n" .
421 $this->_join . " \n" .
422 $this->_query['condition'] . " \n" .
423 $this->_query['group_by'] . " \n" .
424 $this->_query['having'] . " \n" .
425 $this->_query['order_by'] . " \n";
427 if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
428 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
429 /* PEAR DB specific */
431 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
432 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
435 /* theoretically MDB2! */
436 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
437 $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
444 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
445 $this->debug("CHECK autofetchd $n", "find", 1);
451 if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
452 // clear up memory if nothing found!?
453 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
456 if ($n && $this->N > 0 ) {
457 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
458 $this->debug("ABOUT TO AUTOFETCH", "find", 1);
460 $fs = $this->fetch();
461 // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
462 // - hence find() also returns false..
463 $ret = ($ret === true) ? $fs : $ret;
465 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
466 $this->debug("DONE", "find", 1);
468 $this->_query = $query_before;
473 * fetches next row into this objects var's
475 * returns 1 on success 0 on failure
480 * $object = new mytable();
481 * $object->name = "fred";
484 * while ($object->fetch()) {
486 * $store[] = $object; // builds an array of object lines.
489 * to add features to a fetch
490 * function fetch () {
491 * $ret = parent::fetch();
492 * $this->date_formated = date('dmY',$this->date);
497 * @return boolean on success
502 global $_DB_DATAOBJECT;
503 if (empty($_DB_DATAOBJECT['CONFIG'])) {
504 DB_DataObject::_loadConfig();
506 if (empty($this->N)) {
507 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
508 $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
513 if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
514 !is_object($result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
516 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
517 $this->debug('fetched on object after fetch completed (no results found)');
523 $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
524 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
525 $this->debug(serialize($array),"FETCH");
528 // fetched after last row..
529 if ($array === null) {
530 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
531 $t= explode(' ',microtime());
533 $this->debug("Last Data Fetch'ed after " .
534 ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
538 // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
539 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
541 // we need to keep a copy of resultfields locally so toArray() still works
542 // however we dont want to keep it in the global cache..
544 if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
545 $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
546 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
548 // this is probably end of data!!
549 //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
552 // make sure resultFields is always empty..
553 $this->_resultFields = false;
555 if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
556 // note: we dont declare this to keep the print_r size down.
557 $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
560 foreach($array as $k=>$v) {
561 $kk = str_replace(".", "_", $k);
562 $kk = str_replace(" ", "_", $kk);
563 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
564 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
566 $this->$kk = $array[$k];
570 $this->_link_loaded=false;
571 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
572 $this->debug("{$this->__table} DONE", "fetchrow",2);
574 if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
575 $this->_query = false;
581 * Adds a condition to the WHERE statement, defaults to AND
583 * $object->whereAdd(); //reset or cleaer ewhwer
584 * $object->whereAdd("ID > 20");
585 * $object->whereAdd("age > 20","OR");
587 * @param string $cond condition
588 * @param string $logic optional logic "OR" (defaults to "AND")
590 * @return string|PEAR::Error - previous condition or Error when invalid args found
592 function whereAdd($cond = false, $logic = 'AND')
594 // for PHP5.2.3 - there is a bug with setting array properties of an object.
595 $_query = $this->_query;
597 if (!isset($this->_query) || ($_query === false)) {
598 return $this->raiseError(
599 "You cannot do two queries on the same object (clone it before finding)",
600 DB_DATAOBJECT_ERROR_INVALIDARGS);
603 if ($cond === false) {
604 $r = $this->_query['condition'];
605 $_query['condition'] = '';
606 $this->_query = $_query;
607 return preg_replace('/^\s+WHERE\s+/','',$r);
609 // check input...= 0 or ' ' == error!
611 return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
613 $r = $_query['condition'];
614 if ($_query['condition']) {
615 $_query['condition'] .= " {$logic} ( {$cond} )";
616 $this->_query = $_query;
619 $_query['condition'] = " WHERE ( {$cond} ) ";
620 $this->_query = $_query;
625 * Adds a order by condition
627 * $object->orderBy(); //clears order by
628 * $object->orderBy("ID");
629 * $object->orderBy("ID,age");
631 * @param string $order Order
633 * @return none|PEAR::Error - invalid args only
635 function orderBy($order = false)
637 if ($this->_query === false) {
639 "You cannot do two queries on the same object (copy it before finding)",
640 DB_DATAOBJECT_ERROR_INVALIDARGS);
643 if ($order === false) {
644 $this->_query['order_by'] = '';
647 // check input...= 0 or ' ' == error!
649 return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
652 if (!$this->_query['order_by']) {
653 $this->_query['order_by'] = " ORDER BY {$order} ";
656 $this->_query['order_by'] .= " , {$order}";
660 * Adds a group by condition
662 * $object->groupBy(); //reset the grouping
663 * $object->groupBy("ID DESC");
664 * $object->groupBy("ID,age");
666 * @param string $group Grouping
668 * @return none|PEAR::Error - invalid args only
670 function groupBy($group = false)
672 if ($this->_query === false) {
674 "You cannot do two queries on the same object (copy it before finding)",
675 DB_DATAOBJECT_ERROR_INVALIDARGS);
678 if ($group === false) {
679 $this->_query['group_by'] = '';
682 // check input...= 0 or ' ' == error!
684 return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
688 if (!$this->_query['group_by']) {
689 $this->_query['group_by'] = " GROUP BY {$group} ";
692 $this->_query['group_by'] .= " , {$group}";
696 * Adds a having clause
698 * $object->having(); //reset the grouping
699 * $object->having("sum(value) > 0 ");
701 * @param string $having condition
703 * @return none|PEAR::Error - invalid args only
705 function having($having = false)
707 if ($this->_query === false) {
709 "You cannot do two queries on the same object (copy it before finding)",
710 DB_DATAOBJECT_ERROR_INVALIDARGS);
713 if ($having === false) {
714 $this->_query['having'] = '';
717 // check input...= 0 or ' ' == error!
718 if (!trim($having)) {
719 return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
723 if (!$this->_query['having']) {
724 $this->_query['having'] = " HAVING {$having} ";
727 $this->_query['having'] .= " AND {$having}";
733 * $boject->limit(); // clear limit
734 * $object->limit(12);
735 * $object->limit(12,10);
737 * Note this will emit an error on databases other than mysql/postgress
738 * as there is no 'clean way' to implement it. - you should consider refering to
739 * your database manual to decide how you want to implement it.
741 * @param string $a limit start (or number), or blank to reset
742 * @param string $b number
744 * @return none|PEAR::Error - invalid args only
746 function limit($a = null, $b = null)
748 if ($this->_query === false) {
750 "You cannot do two queries on the same object (copy it before finding)",
751 DB_DATAOBJECT_ERROR_INVALIDARGS);
756 $this->_query['limit_start'] = '';
757 $this->_query['limit_count'] = '';
760 // check input...= 0 or ' ' == error!
761 if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
762 || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
763 return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
765 global $_DB_DATAOBJECT;
767 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
769 $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
770 $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
775 * Adds a select columns
777 * $object->selectAdd(); // resets select to nothing!
778 * $object->selectAdd("*"); // default select
779 * $object->selectAdd("unixtime(DATE) as udate");
780 * $object->selectAdd("DATE");
782 * to prepend distict:
783 * $object->selectAdd('distinct ' . $object->selectAdd());
787 * @return mixed null or old string if you reset it.
789 function selectAdd($k = null)
791 if ($this->_query === false) {
793 "You cannot do two queries on the same object (copy it before finding)",
794 DB_DATAOBJECT_ERROR_INVALIDARGS);
798 $old = $this->_query['data_select'];
799 $this->_query['data_select'] = '';
803 // check input...= 0 or ' ' == error!
805 return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
808 if ($this->_query['data_select']) {
809 $this->_query['data_select'] .= ', ';
811 $this->_query['data_select'] .= " $k ";
814 * Adds multiple Columns or objects to select with formating.
816 * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
817 * // note with null it will also clear the '*' default select
818 * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
819 * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
820 * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
821 * objectTableName.colnameA as prefix_colnameA
823 * @param array|object|null the array or object to take column names from.
824 * @param string format in sprintf format (use %s for the colname)
825 * @param string table name eg. if you have joinAdd'd or send $from as an array.
829 function selectAs($from = null,$format = '%s',$tableName=false)
831 global $_DB_DATAOBJECT;
833 if ($this->_query === false) {
835 "You cannot do two queries on the same object (copy it before finding)",
836 DB_DATAOBJECT_ERROR_INVALIDARGS);
840 if ($from === null) {
847 $table = $this->__table;
848 if (is_object($from)) {
849 $table = $from->__table;
850 $from = array_keys($from->table());
853 if ($tableName !== false) {
857 if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
859 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
860 $s = $DB->quoteIdentifier($s);
861 $format = $DB->quoteIdentifier($format);
863 foreach ($from as $k) {
864 $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
866 $this->_query['data_select'] .= "\n";
869 * Insert the current objects variables into the database
871 * Returns the ID of the inserted element (if auto increment or sequences are used.)
875 * Designed to be extended
877 * $object = new mytable();
878 * $object->name = "fred";
879 * echo $object->insert();
882 * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
886 global $_DB_DATAOBJECT;
888 // we need to write to the connection (For nextid) - so us the real
889 // one not, a copyied on (as ret-by-ref fails with overload!)
891 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
895 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
897 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
899 $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
900 $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
903 $this->raiseError("insert:No table definition for {$this->__table}",
904 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
907 $options = &$_DB_DATAOBJECT['CONFIG'];
914 $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]) ?
915 $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] :
916 $this->sequenceKey();
918 $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
919 $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
920 $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
922 $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
925 // nativeSequences or Sequences..
927 // big check for using sequences
929 if (($key !== false) && !$useNative) {
932 $keyvalue = $DB->nextId($this->__table);
934 $f = $DB->getOption('seqname_format');
935 $DB->setOption('seqname_format','%s');
936 $keyvalue = $DB->nextId($seq);
937 $DB->setOption('seqname_format',$f);
939 if (PEAR::isError($keyvalue)) {
940 $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
943 $this->$key = $keyvalue;
948 foreach($items as $k => $v) {
950 // if we are using autoincrement - skip the column...
951 if ($key && ($k == $key) && $useNative) {
956 if (!isset($this->$k)) {
959 // dont insert data into mysql timestamps
960 // use query() if you really want to do this!!!!
961 if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
970 $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
972 if (is_a($this->$k,'DB_DataObject_Cast')) {
973 $value = $this->$k->toString($v,$DB);
974 if (PEAR::isError($value)) {
975 $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
984 if (!isset($options['disable_null_strings']) && is_string($this->$k) && (strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
988 // DATE is empty... on a col. that can be null..
989 // note: this may be usefull for time as well..
991 (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
992 !($v & DB_DATAOBJECT_NOTNULL)) {
999 if ($v & DB_DATAOBJECT_STR) {
1000 $rightq .= $this->_quote((string) (
1001 ($v & DB_DATAOBJECT_BOOL) ?
1002 // this is thanks to the braindead idea of postgres to
1003 // use t/f for boolean.
1004 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
1009 if (is_numeric($this->$k)) {
1010 $rightq .=" {$this->$k} ";
1013 /* flag up string values - only at debug level... !!!??? */
1014 if (is_object($this->$k) || is_array($this->$k)) {
1015 $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k,true),'ERROR');
1018 // at present we only cast to integers
1019 // - V2 may store additional data about float/int
1020 $rightq .= ' ' . intval($this->$k) . ' ';
1024 // not sure why we let empty insert here.. - I guess to generate a blank row..
1027 if ($leftq || $useNative) {
1028 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1030 $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
1034 if (PEAR::isError($r)) {
1035 $this->raiseError($r);
1044 // now do we have an integer key!
1046 if ($key && $useNative) {
1050 $method = "{$dbtype}_insert_id";
1051 $this->$key = $method(
1052 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
1057 // note this is not really thread safe - you should wrapp it with
1058 // transactions = eg.
1059 // $db->query('BEGIN');
1061 // $db->query('COMMIT');
1062 $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1063 $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
1064 $mssql_key = $DB->$method("SELECT @@IDENTITY");
1065 if (PEAR::isError($mssql_key)) {
1066 $this->raiseError($mssql_key);
1069 $this->$key = $mssql_key;
1074 $seq = $DB->getSequenceName(strtolower($this->__table));
1076 $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1077 $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
1078 $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
1081 if (PEAR::isError($pgsql_key)) {
1082 $this->raiseError($pgsql_key);
1085 $this->$key = $pgsql_key;
1089 $this->$key = array_shift (
1092 "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
1093 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
1105 if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
1106 $this->_clear_cache();
1113 $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1118 * Updates current objects variables into the database
1119 * uses the keys() to decide how to update
1120 * Returns the true on success
1124 * $object = DB_DataObject::factory('mytable');
1125 * $object->get("ID",234);
1126 * $object->email="testing@test.com";
1127 * if(!$object->update())
1128 * echo "UPDATE FAILED";
1130 * to only update changed items :
1131 * $dataobject->get(132);
1132 * $original = $dataobject; // clone/copy it..
1133 * $dataobject->setFrom($_POST);
1134 * if ($dataobject->validate()) {
1135 * $dataobject->update($original);
1136 * } // otherwise an error...
1138 * performing global updates:
1139 * $object = DB_DataObject::factory('mytable');
1140 * $object->status = "dead";
1141 * $object->whereAdd('age > 150');
1142 * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
1144 * @param object dataobject (optional) | DB_DATAOBJECT_WHEREADD_ONLY - used to only update changed items.
1146 * @return int rows affected or false on failure
1148 function update($dataObject = false)
1150 global $_DB_DATAOBJECT;
1151 // connect will load the config!
1155 $original_query = $this->_query;
1157 $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
1158 $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
1160 // only apply update against sequence key if it is set?????
1162 $seq = $this->sequenceKey();
1163 if ($seq[0] !== false) {
1164 $keys = array($seq[0]);
1165 if (empty($this->{$keys[0]}) && $dataObject !== true) {
1166 $this->raiseError("update: trying to perform an update without
1167 the key set, and argument to update is not
1168 DB_DATAOBJECT_WHEREADD_ONLY
1169 ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1173 $keys = $this->keys();
1178 $this->raiseError("update:No table definition for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1185 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1186 $dbtype = $DB->dsn["phptype"];
1187 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1188 $options = $_DB_DATAOBJECT['CONFIG'];
1191 foreach($items as $k => $v) {
1192 if (!isset($this->$k)) {
1195 // ignore stuff thats
1197 // dont write things that havent changed..
1198 if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
1202 // - dont write keys to left.!!!
1203 if (in_array($k,$keys)) {
1207 // dont insert data into mysql timestamps
1208 // use query() if you really want to do this!!!!
1209 if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1218 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
1220 if (is_a($this->$k,'DB_DataObject_Cast')) {
1221 $value = $this->$k->toString($v,$DB);
1222 if (PEAR::isError($value)) {
1223 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
1226 $settings .= "$kSql = $value ";
1230 // special values ... at least null is handled...
1231 if (!isset($options['disable_null_strings']) && (strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
1232 $settings .= "$kSql = NULL ";
1235 // DATE is empty... on a col. that can be null..
1236 // note: this may be usefull for time as well..
1238 (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
1239 !($v & DB_DATAOBJECT_NOTNULL)) {
1241 $settings .= "$kSql = NULL ";
1246 if ($v & DB_DATAOBJECT_STR) {
1247 $settings .= "$kSql = ". $this->_quote((string) (
1248 ($v & DB_DATAOBJECT_BOOL) ?
1249 // this is thanks to the braindead idea of postgres to
1250 // use t/f for boolean.
1251 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
1256 if (is_numeric($this->$k)) {
1257 $settings .= "$kSql = {$this->$k} ";
1260 // at present we only cast to integers
1261 // - V2 may store additional data about float/int
1262 $settings .= "$kSql = " . intval($this->$k) . ' ';
1266 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1267 $this->debug("got keys as ".serialize($keys),3);
1269 if ($dataObject !== true) {
1270 $this->_build_condition($items,$keys);
1272 // prevent wiping out of data!
1273 if (empty($this->_query['condition'])) {
1274 $this->raiseError("update: global table update not available
1275 do \$do->whereAdd('1=1'); if you really want to do that.
1276 ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1283 // echo " $settings, $this->condition ";
1284 if ($settings && isset($this->_query) && $this->_query['condition']) {
1286 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1288 $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
1290 // restore original query conditions.
1291 $this->_query = $original_query;
1293 if (PEAR::isError($r)) {
1294 $this->raiseError($r);
1301 $this->_clear_cache();
1304 // restore original query conditions.
1305 $this->_query = $original_query;
1307 // if you manually specified a dataobject, and there where no changes - then it's ok..
1308 if ($dataObject !== false) {
1313 "update: No Data specifed for query $settings , {$this->_query['condition']}",
1314 DB_DATAOBJECT_ERROR_NODATA);
1319 * Deletes items from table which match current objects variables
1321 * Returns the true on success
1325 * Designed to be extended
1327 * $object = new mytable();
1329 * echo $object->delete(); // builds a conditon
1331 * $object = new mytable();
1332 * $object->whereAdd('age > 12');
1333 * $object->limit(1);
1334 * $object->orderBy('age DESC');
1335 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
1337 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1338 * we will build the condition only using the whereAdd's. Default is to
1339 * build the condition only using the object parameters.
1342 * @return mixed True on success, false on failure, 0 on no data affected
1344 function delete($useWhere = false)
1346 global $_DB_DATAOBJECT;
1347 // connect will load the config!
1349 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1350 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1352 $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
1356 $keys = $this->keys();
1357 $this->_query = array(); // as it's probably unset!
1358 $this->_query['condition'] = ''; // default behaviour not to use where condition
1359 $this->_build_condition($this->table(),$keys);
1360 // if primary keys are not set then use data from rest of object.
1361 if (!$this->_query['condition']) {
1362 $this->_build_condition($this->table(),array(),$keys);
1368 // don't delete without a condition
1369 if (($this->_query !== false) && $this->_query['condition']) {
1371 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1372 $sql = "DELETE FROM {$table} {$this->_query['condition']}{$extra_cond}";
1376 if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
1378 if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
1379 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
1381 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
1385 $DB->setLimit( $this->_query['limit_count'],$this->_query['limit_start']);
1391 $r = $this->_query($sql);
1394 if (PEAR::isError($r)) {
1395 $this->raiseError($r);
1401 $this->_clear_cache();
1404 $this->raiseError("delete: No condition specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1410 * fetches a specific row into this object variables
1412 * Not recommended - better to use fetch()
1414 * Returens true on success
1416 * @param int $row row
1418 * @return boolean true on success
1420 function fetchRow($row = null)
1422 global $_DB_DATAOBJECT;
1423 if (empty($_DB_DATAOBJECT['CONFIG'])) {
1424 $this->_loadConfig();
1426 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1427 $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
1429 if (!$this->__table) {
1430 $this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1433 if ($row === null) {
1434 $this->raiseError("fetchrow: No row specified", DB_DATAOBJECT_ERROR_INVALIDARGS);
1438 $this->raiseError("fetchrow: No results avaiable", DB_DATAOBJECT_ERROR_NODATA);
1441 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1442 $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
1446 $result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
1447 $array = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC,$row);
1448 if (!is_array($array)) {
1449 $this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
1453 foreach($array as $k => $v) {
1454 $kk = str_replace(".", "_", $k);
1455 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1456 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
1458 $this->$kk = $array[$k];
1461 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1462 $this->debug("{$this->__table} DONE", "fetchrow", 3);
1468 * Find the number of results from a simple query
1472 * $object = new mytable();
1473 * $object->name = "fred";
1474 * echo $object->count();
1475 * echo $object->count(true); // dont use object vars.
1476 * echo $object->count('distinct mycol'); count distinct mycol.
1477 * echo $object->count('distinct mycol',true); // dont use object vars.
1478 * echo $object->count('distinct'); // count distinct id (eg. the primary key)
1481 * @param bool|string (optional)
1482 * (true|false => see below not on whereAddonly)
1484 * "DISTINCT" => does a distinct count on the tables 'key' column
1485 * otherwise => normally it counts primary keys - you can use
1486 * this to do things like $do->count('distinct mycol');
1488 * @param bool $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1489 * we will build the condition only using the whereAdd's. Default is to
1490 * build the condition using the object parameters as well.
1495 function count($countWhat = false,$whereAddOnly = false)
1497 global $_DB_DATAOBJECT;
1499 if (is_bool($countWhat)) {
1500 $whereAddOnly = $countWhat;
1504 $items = $t->table();
1506 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1509 if (!isset($t->_query)) {
1511 "You cannot do run count after you have run fetch()",
1512 DB_DATAOBJECT_ERROR_INVALIDARGS);
1516 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1519 if (!$whereAddOnly && $items) {
1520 $t->_build_condition($items);
1522 $keys = $this->keys();
1524 if (!$keys[0] && !is_string($countWhat)) {
1526 "You cannot do run count without keys - use \$do->keys('id');",
1527 DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
1531 $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1532 $key_col = ($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]);
1533 $as = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
1535 // support distinct on default keys.
1536 $countWhat = (strtoupper($countWhat) == 'DISTINCT') ?
1537 "DISTINCT {$table}.{$key_col}" : $countWhat;
1539 $countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
1542 "SELECT count({$countWhat}) as $as
1543 FROM $table {$t->_join} {$t->_query['condition']}");
1544 if (PEAR::isError($r)) {
1548 $result = &$_DB_DATAOBJECT['RESULTS'][$t->_DB_resultid];
1549 $l = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ORDERED);
1550 // free the results - essential on oracle.
1557 * sends raw query to database
1559 * Since _query has to be a private 'non overwriteable method', this is a relay
1561 * @param string $string SQL Query
1563 * @return void or DB_Error
1565 function query($string)
1567 return $this->_query($string);
1572 * an escape wrapper around DB->escapeSimple()
1573 * can be used when adding manual queries or clauses
1575 * $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
1577 * @param string $string value to be escaped
1578 * @param bool $likeEscape escapes % and _ as well. - so like queries can be protected.
1582 function escape($string, $likeEscape=false)
1584 global $_DB_DATAOBJECT;
1586 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1587 // mdb2 uses escape...
1588 $dd = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
1589 $ret = ($dd == 'DB') ? $DB->escapeSimple($string) : $DB->escape($string);
1591 $ret = str_replace(array('_','%'), array('\_','\%'), $ret);
1597 /* ==================================================== */
1598 /* Major Private Vars */
1599 /* ==================================================== */
1602 * The Database connection dsn (as described in the PEAR DB)
1603 * only used really if you are writing a very simple application/test..
1604 * try not to use this - it is better stored in configuration files..
1609 var $_database_dsn = '';
1612 * The Database connection id (md5 sum of databasedsn)
1617 var $_database_dsn_md5 = '';
1621 * created in __connection
1626 var $_database = '';
1632 * This replaces alot of the private variables
1633 * used to build a query, it is unset after find() is run.
1640 var $_query = array(
1641 'condition' => '', // the WHERE condition
1642 'group_by' => '', // the GROUP BY condition
1643 'order_by' => '', // the ORDER BY condition
1644 'having' => '', // the HAVING condition
1645 'limit_start' => '', // the LIMIT condition
1646 'limit_count' => '', // the LIMIT condition
1647 'data_select' => '*', // the columns to be SELECTed
1654 * Database result id (references global $_DB_DataObject[results]
1662 * ResultFields - on the last call to fetch(), resultfields is sent here,
1663 * so we can clean up the memory.
1668 var $_resultFields = false;
1671 /* ============================================================== */
1672 /* Table definition layer (started of very private but 'came out'*/
1673 /* ============================================================== */
1676 * Autoload or manually load the table definitions
1680 * DB_DataObject::databaseStructure( 'databasename',
1681 * parse_ini_file('mydb.ini',true),
1682 * parse_ini_file('mydb.link.ini',true));
1684 * obviously you dont have to use ini files.. (just return array similar to ini files..)
1686 * It should append to the table structure array
1689 * @param optional string name of database to assign / read
1690 * @param optional array structure of database, and keys
1691 * @param optional array table links
1694 * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
1695 * or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
1697 function databaseStructure()
1700 global $_DB_DATAOBJECT;
1704 if ($args = func_get_args()) {
1706 if (count($args) == 1) {
1708 // this returns all the tables and their structure..
1709 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1710 $this->debug("Loading Generator as databaseStructure called with args",1);
1713 $x = new DB_DataObject;
1714 $x->_database = $args[0];
1716 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1718 $tables = $DB->getListOf('tables');
1719 class_exists('DB_DataObject_Generator') ? '' :
1720 require_once 'DB/DataObject/Generator.php';
1722 foreach($tables as $table) {
1723 $y = new DB_DataObject_Generator;
1724 $y->fillTableSchema($x->_database,$table);
1726 return $_DB_DATAOBJECT['INI'][$x->_database];
1729 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
1730 $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
1732 if (isset($args[1])) {
1733 $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
1734 $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
1743 if (!$this->_database) {
1748 if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
1750 // database loaded - but this is table is not available..
1752 empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])
1753 && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
1755 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1756 $this->debug("Loading Generator to fetch Schema",1);
1758 class_exists('DB_DataObject_Generator') ? '' :
1759 require_once 'DB/DataObject/Generator.php';
1762 $x = new DB_DataObject_Generator;
1763 $x->fillTableSchema($this->_database,$this->__table);
1769 if (empty($_DB_DATAOBJECT['CONFIG'])) {
1770 DB_DataObject::_loadConfig();
1773 // if you supply this with arguments, then it will take those
1774 // as the database and links array...
1776 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
1777 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
1780 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
1781 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
1782 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
1783 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
1788 foreach ($schemas as $ini) {
1789 if (file_exists($ini) && is_file($ini)) {
1790 $_DB_DATAOBJECT['INI'][$this->_database] = parse_ini_file($ini, true);
1791 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1792 if (!is_readable ($ini)) {
1793 $this->debug("ini file is not readable: $ini","databaseStructure",1);
1795 $this->debug("Loaded ini file: $ini","databaseStructure",1);
1799 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1800 $this->debug("Missing ini file: $ini","databaseStructure",1);
1805 // now have we loaded the structure..
1807 if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
1810 // - if not try building it..
1811 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
1812 class_exists('DB_DataObject_Generator') ? '' :
1813 require_once 'DB/DataObject/Generator.php';
1815 $x = new DB_DataObject_Generator;
1816 $x->fillTableSchema($this->_database,$this->__table);
1817 // should this fail!!!???
1820 $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
1821 "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
1822 // we have to die here!! - it causes chaos if we dont (including looping forever!)
1823 $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);
1833 * Return or assign the name of the current table
1836 * @param string optinal table name to set
1838 * @return string The name of the current table
1840 function tableName()
1842 $args = func_get_args();
1844 $this->__table = $args[0];
1846 return $this->__table;
1850 * Return or assign the name of the current database
1852 * @param string optional database name to set
1854 * @return string The name of the current database
1858 $args = func_get_args();
1860 $this->_database = $args[0];
1862 return $this->_database;
1866 * get/set an associative array of table columns
1869 * @param array key=>type array
1870 * @return array (associative)
1875 // for temporary storage of database fields..
1876 // note this is not declared as we dont want to bloat the print_r output
1877 $args = func_get_args();
1879 $this->_database_fields = $args[0];
1881 if (isset($this->_database_fields)) {
1882 return $this->_database_fields;
1886 global $_DB_DATAOBJECT;
1887 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
1891 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
1892 return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
1895 $this->databaseStructure();
1899 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
1900 $ret = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
1907 * get/set an array of table primary keys
1909 * set usage: $do->keys('id','code');
1911 * This is defined in the table definition if it gets it wrong,
1912 * or you do not want to use ini tables, you can override this.
1913 * @param string optional set the key
1914 * @param * optional set more keys
1920 // for temporary storage of database fields..
1921 // note this is not declared as we dont want to bloat the print_r output
1922 $args = func_get_args();
1924 $this->_database_keys = $args;
1926 if (isset($this->_database_keys)) {
1927 return $this->_database_keys;
1930 global $_DB_DATAOBJECT;
1931 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
1934 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
1935 return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
1937 $this->databaseStructure();
1939 if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
1940 return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
1945 * get/set an sequence key
1947 * by default it returns the first key from keys()
1948 * set usage: $do->sequenceKey('id',true);
1950 * override this to return array(false,false) if table has no real sequence key.
1952 * @param string optional the key sequence/autoinc. key
1953 * @param boolean optional use native increment. default false
1954 * @param false|string optional native sequence name
1956 * @return array (column,use_native,sequence_name)
1958 function sequenceKey()
1960 global $_DB_DATAOBJECT;
1963 if (!$this->_database) {
1967 if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
1968 $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
1972 $args = func_get_args();
1974 $args[1] = isset($args[1]) ? $args[1] : false;
1975 $args[2] = isset($args[2]) ? $args[2] : false;
1976 $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = $args;
1978 if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table])) {
1979 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table];
1981 // end call setting (eg. $do->sequenceKeys(a,b,c); )
1986 $keys = $this->keys();
1988 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]
1989 = array(false,false,false);
1993 $table = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
1994 $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
1996 $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
2004 if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table])) {
2005 $usekey = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table];
2006 if (strpos($usekey,':') !== false) {
2007 list($usekey,$seqname) = explode(':',$usekey);
2012 // if the key is not an integer - then it's not a sequence or native
2013 if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
2014 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,false);
2018 if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
2019 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
2020 if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
2021 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2023 if (is_string($ignore)) {
2024 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
2026 if (in_array($this->__table,$ignore)) {
2027 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2032 $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
2034 // if you are using an old ini file - go back to old behaviour...
2035 if (is_numeric($realkeys[$usekey])) {
2036 $realkeys[$usekey] = 'N';
2039 // multiple unique primary keys without a native sequence...
2040 if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
2041 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2043 // use native sequence keys...
2044 // technically postgres native here...
2045 // we need to get the new improved tabledata sorted out first.
2047 if ( in_array($dbtype , array('psql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
2048 ($table[$usekey] & DB_DATAOBJECT_INT) &&
2049 isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
2051 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,true,$seqname);
2053 // if not a native autoinc, and we have not assumed all primary keys are sequence
2054 if (($realkeys[$usekey] != 'N') &&
2055 !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
2056 return array(false,false,false);
2058 // I assume it's going to try and be a nextval DB sequence.. (not native)
2059 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,false,$seqname);
2064 /* =========================================================== */
2065 /* Major Private Methods - the core part! */
2066 /* =========================================================== */
2071 * clear the cache values for this class - normally done on insert/update etc.
2076 function _clear_cache()
2078 global $_DB_DATAOBJECT;
2080 $class = strtolower(get_class($this));
2082 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2083 $this->debug("Clearing Cache for ".$class,1);
2086 if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
2087 unset($_DB_DATAOBJECT['CACHE'][$class]);
2093 * backend wrapper for quoting, as MDB2 and DB do it differently...
2096 * @return string quoted
2099 function _quote($str)
2101 global $_DB_DATAOBJECT;
2102 return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
2103 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
2104 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
2105 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
2110 * connects to the database
2113 * TODO: tidy this up - This has grown to support a number of connection options like
2114 * a) dynamic changing of ini file to change which database to connect to
2115 * b) multi data via the table_{$table} = dsn ini option
2116 * c) session based storage.
2119 * @return true | PEAR::error
2123 global $_DB_DATAOBJECT;
2124 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2125 $this->_loadConfig();
2127 // Set database driver for reference
2128 $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
2129 // is it already connected ?
2131 if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2132 if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2133 return $this->raiseError(
2134 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
2135 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2140 if (!$this->_database) {
2141 $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2142 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2144 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2145 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2146 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2150 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2151 && is_file($this->_database)) {
2152 $this->_database = basename($this->_database);
2154 if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase') {
2155 $this->_database = substr(basename($this->_database), 0, -4);
2159 // theoretically we have a md5, it's listed in connections and it's not an error.
2160 // so everything is ok!
2165 // it's not currently connected!
2166 // try and work out what to use for the dsn !
2168 $options= &$_DB_DATAOBJECT['CONFIG'];
2169 $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
2172 if (!$this->_database) {
2173 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
2175 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2176 $this->debug("Checking for database database_{$this->_database} in options","CONNECT");
2179 if ($this->_database && !empty($options["database_{$this->_database}"])) {
2181 $dsn = $options["database_{$this->_database}"];
2182 } else if (!empty($options['database'])) {
2183 $dsn = $options['database'];
2187 // if still no database...
2189 return $this->raiseError(
2190 "No database name / dsn found anywhere",
2191 DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
2197 if (is_string($dsn)) {
2198 $this->_database_dsn_md5 = md5($dsn);
2200 /// support array based dsn's
2201 $this->_database_dsn_md5 = md5(serialize($dsn));
2204 if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2205 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2206 $this->debug("USING CACHED CONNECTION", "CONNECT",3);
2208 if (!$this->_database) {
2210 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2211 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2212 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2213 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2215 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2216 && is_file($this->_database))
2218 $this->_database = basename($this->_database);
2223 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2224 $this->debug("NEW CONNECTION", "CONNECT",3);
2225 /* actualy make a connection */
2226 $this->debug(print_r($dsn,true) ." {$this->_database_dsn_md5}", "CONNECT",3);
2229 // Note this is verbose deliberatly!
2231 if ($db_driver == 'DB') {
2233 /* PEAR DB connect */
2235 // this allows the setings of compatibility on DB
2236 $db_options = PEAR::getStaticProperty('DB','options');
2237 require_once 'DB.php';
2239 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &DB::connect($dsn,$db_options);
2241 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &DB::connect($dsn);
2245 /* assumption is MDB2 */
2246 require_once 'MDB2.php';
2247 // this allows the setings of compatibility on MDB2
2248 $db_options = PEAR::getStaticProperty('MDB2','options');
2249 $db_options = is_array($db_options) ? $db_options : array();
2250 $db_options['portability'] = isset($db_options['portability'] )
2251 ? $db_options['portability'] : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
2252 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &MDB2::connect($dsn,$db_options);
2257 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2258 $this->debug(serialize($_DB_DATAOBJECT['CONNECTIONS']), "CONNECT",5);
2260 if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2261 $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED",5);
2262 return $this->raiseError(
2263 "Connect failed, turn on debugging to 5 see why",
2264 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2269 if (!$this->_database) {
2270 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2272 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
2273 ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
2274 : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2277 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
2278 && is_file($this->_database))
2280 $this->_database = basename($this->_database);
2284 // Oracle need to optimize for portibility - not sure exactly what this does though :)
2285 $c = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2291 * sends query to database - this is the private one that must work
2292 * - internal functions use this rather than $this->query()
2294 * @param string $string
2296 * @return mixed none or PEAR_Error
2298 function _query($string)
2300 global $_DB_DATAOBJECT;
2304 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2306 $options = &$_DB_DATAOBJECT['CONFIG'];
2308 $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
2309 'DB': $_DB_DATAOBJECT['CONFIG']['db_driver'];
2311 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2312 $this->debug($string,$log="QUERY");
2316 if (strtoupper($string) == 'BEGIN') {
2317 if ($_DB_driver == 'DB') {
2318 $DB->autoCommit(false);
2320 $DB->beginTransaction();
2322 // db backend adds begin anyway from now on..
2325 if (strtoupper($string) == 'COMMIT') {
2326 $res = $DB->commit();
2327 if ($_DB_driver == 'DB') {
2328 $DB->autoCommit(true);
2333 if (strtoupper($string) == 'ROLLBACK') {
2335 if ($_DB_driver == 'DB') {
2336 $DB->autoCommit(true);
2342 if (!empty($options['debug_ignore_updates']) &&
2343 (strtolower(substr(trim($string), 0, 6)) != 'select') &&
2344 (strtolower(substr(trim($string), 0, 4)) != 'show') &&
2345 (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
2347 $this->debug('Disabling Update as you are in debug mode');
2348 return $this->raiseError("Disabling Update as you are in debug mode", null) ;
2351 //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
2352 // this will only work when PEAR:DB supports it.
2353 //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
2357 $t= explode(' ',microtime());
2358 $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
2363 if ($_DB_driver == 'DB') {
2364 $result = $DB->query($string);
2366 switch (strtolower(substr(trim($string),0,6))) {
2371 $result = $DB->exec($string);
2375 $result = $DB->query($string);
2380 // try to reconnect, at most 3 times
2382 if (is_a($result, 'PEAR_Error')
2383 AND $result->getCode() == DB_ERROR_NODBSELECTED
2387 $DB->connect($DB->dsn);
2393 if (is_a($result,'PEAR_Error')) {
2394 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2395 $this->debug($result->toString(), "Query Error",1 );
2397 return $this->raiseError($result);
2399 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2400 $t= explode(' ',microtime());
2401 $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
2402 $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query',1);
2404 switch (strtolower(substr(trim($string),0,6))) {
2408 if ($_DB_driver == 'DB') {
2410 return $DB->affectedRows();
2414 if (is_object($result)) {
2415 // lets hope that copying the result object is OK!
2417 $_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
2418 $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
2419 $this->_DB_resultid = $_DB_resultid;
2422 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2423 $this->debug(serialize($result), 'RESULT',5);
2425 if (method_exists($result, 'numrows')) {
2426 if ($_DB_driver == 'DB') {
2427 $DB->expectError(DB_ERROR_UNSUPPORTED);
2429 $DB->expectError(MDB2_ERROR_UNSUPPORTED);
2431 $this->N = $result->numrows();
2432 if (is_a($this->N,'PEAR_Error')) {
2440 * Builds the WHERE based on the values of of this object
2442 * @param mixed $keys
2443 * @param array $filter (used by update to only uses keys in this filter list).
2444 * @param array $negative_filter (used by delete to prevent deleting using the keys mentioned..)
2448 function _build_condition($keys, $filter = array(),$negative_filter=array())
2450 global $_DB_DATAOBJECT;
2452 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2454 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
2455 $options = $_DB_DATAOBJECT['CONFIG'];
2457 // if we dont have query vars.. - reset them.
2458 if ($this->_query === false) {
2459 $x = new DB_DataObject;
2460 $this->_query= $x->_query;
2463 foreach($keys as $k => $v) {
2464 // index keys is an indexed array
2465 /* these filter checks are a bit suspicious..
2466 - need to check that update really wants to work this way */
2469 if (!in_array($k, $filter)) {
2473 if ($negative_filter) {
2474 if (in_array($k, $negative_filter)) {
2478 if (!isset($this->$k)) {
2482 $kSql = $quoteIdentifiers
2483 ? ( $DB->quoteIdentifier($this->__table) . '.' . $DB->quoteIdentifier($k) )
2484 : "{$this->__table}.{$k}";
2488 if (is_a($this->$k,'DB_DataObject_Cast')) {
2489 $dbtype = $DB->dsn["phptype"];
2490 $value = $this->$k->toString($v,$DB);
2491 if (PEAR::isError($value)) {
2492 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
2495 if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2496 $this->whereAdd(" $kSql IS NULL");
2499 $this->whereAdd(" $kSql = $value");
2503 if (!isset($options['disable_null_strings']) && (strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2504 $this->whereAdd(" $kSql IS NULL");
2509 if ($v & DB_DATAOBJECT_STR) {
2510 $this->whereAdd(" $kSql = " . $this->_quote((string) (
2511 ($v & DB_DATAOBJECT_BOOL) ?
2512 // this is thanks to the braindead idea of postgres to
2513 // use t/f for boolean.
2514 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
2519 if (is_numeric($this->$k)) {
2520 $this->whereAdd(" $kSql = {$this->$k}");
2523 /* this is probably an error condition! */
2524 $this->whereAdd(" $kSql = ".intval($this->$k));
2529 * autoload Class relating to a table
2530 * (depreciated - use ::factory)
2532 * @param string $table table
2534 * @return string classname on Success
2536 function staticAutoloadTable($table)
2538 global $_DB_DATAOBJECT;
2539 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2540 DB_DataObject::_loadConfig();
2542 $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2543 $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
2544 $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2546 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2547 $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
2553 * classic factory method for loading a table class
2554 * usage: $do = DB_DataObject::factory('person')
2555 * WARNING - this may emit a include error if the file does not exist..
2556 * use @ to silence it (if you are sure it is acceptable)
2557 * eg. $do = @DB_DataObject::factory('person')
2559 * table name will eventually be databasename/table
2560 * - and allow modular dataobjects to be written..
2561 * (this also helps proxy creation)
2564 * @param string $table tablename (use blank to create a new instance of the same class.)
2566 * @return DataObject|PEAR_Error
2571 function factory($table = '') {
2572 global $_DB_DATAOBJECT;
2573 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2574 DB_DataObject::_loadConfig();
2577 if ($table === '') {
2578 if (is_a($this,'DB_DataObject') && strlen($this->__table)) {
2579 $table = $this->__table;
2581 return DB_DataObject::raiseError(
2582 "factory did not recieve a table name",
2583 DB_DATAOBJECT_ERROR_INVALIDARGS);
2588 $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2589 $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
2590 $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2592 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2593 $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
2595 // proxy = full|light
2596 if (!$class && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
2597 $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
2598 class_exists('DB_DataObject_Generator') ? '' :
2599 require_once 'DB/DataObject/Generator.php';
2601 $d = new DB_DataObject;
2603 $d->__table = $table;
2604 if (is_a($ret = $d->_connect(), 'PEAR_Error')) {
2608 $x = new DB_DataObject_Generator;
2609 return $x->$proxyMethod( $d->_database, $table);
2613 return DB_DataObject::raiseError(
2614 "factory could not find class $class from $table",
2615 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2623 * @param string $class Class
2625 * @return string classname on Success
2627 function _autoloadClass($class)
2629 global $_DB_DATAOBJECT;
2631 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2632 DB_DataObject::_loadConfig();
2634 $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2635 '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
2637 $table = substr($class,strlen($class_prefix));
2639 // only include the file if it exists - and barf badly if it has parse errors :)
2640 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
2645 if (strpos($_DB_DATAOBJECT['CONFIG']['class_location'],'%s') !== false) {
2646 $file = sprintf($_DB_DATAOBJECT['CONFIG']['class_location'], preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
2648 $file = $_DB_DATAOBJECT['CONFIG']['class_location'].'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2651 if (!file_exists($file)) {
2653 foreach(explode(PATH_SEPARATOR, ini_get('include_path')) as $p) {
2654 if (file_exists("$p/$file")) {
2661 DB_DataObject::raiseError(
2662 "autoload:Could not find class {$class} using class_location value",
2663 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2671 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2674 DB_DataObject::raiseError(
2675 "autoload:Could not autoload {$class}",
2676 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2685 * Have the links been loaded?
2686 * if they have it contains a array of those variables.
2689 * @var boolean | array
2691 var $_link_loaded = false;
2694 * Get the links associate array as defined by the links.ini file.
2698 * Should look a bit like
2699 * [local_col_name] => "related_tablename:related_col_name"
2702 * @return array|null
2703 * array = if there are links defined for this table.
2704 * empty array - if there is a links.ini file, but no links on this table
2705 * null - if no links.ini exists for this database (hence try auto_links).
2707 * @see DB_DataObject::getLinks(), DB_DataObject::getLink()
2712 global $_DB_DATAOBJECT;
2713 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2714 $this->_loadConfig();
2716 // have to connect.. -> otherwise things break later.
2719 if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
2720 return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
2727 // attempt to load links file here..
2729 if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
2730 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
2731 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
2734 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
2735 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
2736 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
2737 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
2742 foreach ($schemas as $ini) {
2745 isset($_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"]) ?
2746 $_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"] :
2747 str_replace('.ini','.links.ini',$ini);
2749 if (empty($_DB_DATAOBJECT['LINKS'][$this->_database]) && file_exists($links) && is_file($links)) {
2750 /* not sure why $links = ... here - TODO check if that works */
2751 $_DB_DATAOBJECT['LINKS'][$this->_database] = parse_ini_file($links, true);
2752 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2753 $this->debug("Loaded links.ini file: $links","links",1);
2756 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2757 $this->debug("Missing links.ini file: $links","links",1);
2764 // if there is no link data at all on the file!
2766 if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
2770 if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
2771 return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
2777 * load related objects
2779 * There are two ways to use this, one is to set up a <dbname>.links.ini file
2780 * into a static property named <dbname>.links and specifies the table joins,
2781 * the other highly dependent on naming columns 'correctly' :)
2782 * using colname = xxxxx_yyyyyy
2783 * xxxxxx = related table; (yyyyy = user defined..)
2784 * looks up table xxxxx, for value id=$this->xxxxx
2785 * stores it in $this->_xxxxx_yyyyy
2786 * you can change what object vars the links are stored in by
2787 * changeing the format parameter
2790 * @param string format (default _%s) where %s is the table name.
2791 * @author Tim White <tim@cyface.com>
2793 * @return boolean , true on success
2795 function getLinks($format = '_%s')
2798 // get table will load the options.
2799 if ($this->_link_loaded) {
2802 $this->_link_loaded = false;
2803 $cols = $this->table();
2804 $links = $this->links();
2809 foreach($links as $key => $match) {
2810 list($table,$link) = explode(':', $match);
2811 $k = sprintf($format, str_replace('.', '_', $key));
2812 // makes sure that '.' is the end of the key;
2813 if ($p = strpos($key,'.')) {
2814 $key = substr($key, 0, $p);
2817 $this->$k = $this->getLink($key, $table, $link);
2819 if (is_object($this->$k)) {
2823 $this->_link_loaded = $loaded;
2826 // this is the autonaming stuff..
2827 // it sends the column name down to getLink and lets that sort it out..
2828 // if there is a links file then it is not used!
2829 // IT IS DEPRECIATED!!!! - USE
2830 if (!is_null($links)) {
2835 foreach (array_keys($cols) as $key) {
2836 if (!($p = strpos($key, '_'))) {
2839 // does the table exist.
2840 $k =sprintf($format, $key);
2841 $this->$k = $this->getLink($key);
2842 if (is_object($this->$k)) {
2846 $this->_link_loaded = $loaded;
2851 * return name from related object
2853 * There are two ways to use this, one is to set up a <dbname>.links.ini file
2854 * into a static property named <dbname>.links and specifies the table joins,
2855 * the other is highly dependant on naming columns 'correctly' :)
2857 * NOTE: the naming convention is depreciated!!! - use links.ini
2859 * using colname = xxxxx_yyyyyy
2860 * xxxxxx = related table; (yyyyy = user defined..)
2861 * looks up table xxxxx, for value id=$this->xxxxx
2862 * stores it in $this->_xxxxx_yyyyy
2864 * you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
2867 * @param string $row either row or row.xxxxx
2868 * @param string $table name of table to look up value in
2869 * @param string $link name of column in other table to match
2870 * @author Tim White <tim@cyface.com>
2872 * @return mixed object on success
2874 function getLink($row, $table = null, $link = false)
2878 // GUESS THE LINKED TABLE.. (if found - recursevly call self)
2880 if ($table === null) {
2881 $links = $this->links();
2883 if (is_array($links)) {
2886 list($table,$link) = explode(':', $links[$row]);
2887 if ($p = strpos($row,".")) {
2888 $row = substr($row,0,$p);
2890 return $this->getLink($row,$table,$link);
2895 "getLink: $row is not defined as a link (normally this is ok)",
2896 DB_DATAOBJECT_ERROR_NODATA);
2899 return $r;// technically a possible error condition?
2902 // use the old _ method - this shouldnt happen if called via getLinks()
2903 if (!($p = strpos($row, '_'))) {
2907 $table = substr($row, 0, $p);
2908 return $this->getLink($row, $table);
2915 if (!isset($this->$row)) {
2916 $this->raiseError("getLink: row not set $row", DB_DATAOBJECT_ERROR_NODATA);
2920 // check to see if we know anything about this table..
2922 $obj = $this->factory($table);
2924 if (!is_a($obj,'DB_DataObject')) {
2926 "getLink:Could not find class for row $row, table $table",
2927 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2931 if ($obj->get($link, $this->$row)) {
2938 if ($obj->get($this->$row)) {
2947 * IS THIS SUPPORTED/USED ANYMORE????
2948 *return a list of options for a linked table
2950 * This is highly dependant on naming columns 'correctly' :)
2951 * using colname = xxxxx_yyyyyy
2952 * xxxxxx = related table; (yyyyy = user defined..)
2953 * looks up table xxxxx, for value id=$this->xxxxx
2954 * stores it in $this->_xxxxx_yyyyy
2957 * @return array of results (empty array on failure)
2959 function &getLinkArray($row, $table = null)
2964 $links = $this->links();
2966 if (is_array($links)) {
2967 if (!isset($links[$row])) {
2971 list($table,$link) = explode(':',$links[$row]);
2973 if (!($p = strpos($row,'_'))) {
2976 $table = substr($row,0,$p);
2980 $c = $this->factory($table);
2982 if (!is_a($c,'DB_DataObject')) {
2984 "getLinkArray:Could not find class for row $row, table $table",
2985 DB_DATAOBJECT_ERROR_INVALIDCONFIG
2990 // if the user defined method list exists - use it...
2991 if (method_exists($c, 'listFind')) {
2992 $c->listFind($this->id);
2996 while ($c->fetch()) {
3003 * The JOIN condition
3011 * joinAdd - adds another dataobject to this, building a joined query.
3013 * example (requires links.ini to be set up correctly)
3014 * // get all the images for product 24
3015 * $i = new DataObject_Image();
3016 * $pi = new DataObjects_Product_image();
3017 * $pi->product_id = 24; // set the product id to 24
3018 * $i->joinAdd($pi); // add the product_image connectoin
3020 * while ($i->fetch()) {
3023 * // an example with 2 joins
3024 * // get all the images linked with products or productgroups
3025 * $i = new DataObject_Image();
3026 * $pi = new DataObject_Product_image();
3027 * $pgi = new DataObject_Productgroup_image();
3029 * $i->joinAdd($pgi);
3031 * while ($i->fetch()) {
3036 * @param optional $obj object |array the joining object (no value resets the join)
3037 * If you use an array here it should be in the format:
3038 * array('local_column','remotetable:remote_column');
3039 * if remotetable does not have a definition, you should
3040 * use @ to hide the include error message..
3043 * @param optional $joinType string | array
3044 * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
3045 * just select ... from a,b,c with no join and
3046 * links are added as where items.
3048 * If second Argument is array, it is assumed to be an associative
3049 * array with arguments matching below = eg.
3050 * 'joinType' => 'INNER',
3053 * 'useWhereAsOn' => false,
3055 * @param optional $joinAs string if you want to select the table as anther name
3056 * useful when you want to select multiple columsn
3057 * from a secondary table.
3059 * @param optional $joinCol string The column on This objects table to match (needed
3060 * if this table links to the child object in
3061 * multiple places eg.
3062 * user->friend (is a link to another user)
3063 * user->mother (is a link to another user..)
3065 * optional 'useWhereAsOn' bool default false;
3066 * convert the where argments from the object being added
3067 * into ON arguments.
3072 * @author Stijn de Reede <sjr@gmx.co.uk>
3074 function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
3076 global $_DB_DATAOBJECT;
3077 if ($obj === false) {
3083 $useWhereAsOn = false;
3084 // support for 2nd argument as an array of options
3085 if (is_array($joinType)) {
3086 // new options can now go in here... (dont forget to document them)
3087 $useWhereAsOn = !empty($joinType['useWhereAsOn']);
3088 $joinCol = isset($joinType['joinCol']) ? $joinType['joinCol'] : $joinCol;
3089 $joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
3090 $joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
3092 // support for array as first argument
3093 // this assumes that you dont have a links.ini for the specified table.
3094 // and it doesnt exist as am extended dataobject!! - experimental.
3096 $ofield = false; // object field
3097 $tfield = false; // this field
3099 if (is_array($obj)) {
3101 list($toTable,$ofield) = explode(':',$obj[1]);
3102 $obj = DB_DataObject::factory($toTable);
3104 if (!$obj || is_a($obj,'PEAR_Error')) {
3105 $obj = new DB_DataObject;
3106 $obj->__table = $toTable;
3109 // set the table items to nothing.. - eg. do not try and match
3110 // things in the child table...???
3114 if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
3115 return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
3117 /* make sure $this->_database is set. */
3119 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3124 /* look up the links for obj table */
3125 //print_r($obj->links());
3126 if (!$ofield && ($olinks = $obj->links())) {
3128 foreach ($olinks as $k => $v) {
3129 /* link contains {this column} = {linked table}:{linked column} */
3130 $ar = explode(':', $v);
3132 // Feature Request #4266 - Allow joins with multiple keys
3134 $links_key_array = strpos($k,',');
3135 if ($links_key_array !== false) {
3136 $k = explode(',', $k);
3139 $ar_array = strpos($ar[1],',');
3140 if ($ar_array !== false) {
3141 $ar[1] = explode(',', $ar[1]);
3144 if ($ar[0] == $this->__table) {
3146 // you have explictly specified the column
3147 // and the col is listed here..
3148 // not sure if 1:1 table could cause probs here..
3150 if ($joinCol !== false) {
3152 "joinAdd: You cannot target a join column in the " .
3153 "'link from' table ({$obj->__table}). " .
3154 "Either remove the fourth argument to joinAdd() ".
3155 "({$joinCol}), or alter your links.ini file.",
3156 DB_DATAOBJECT_ERROR_NODATA);
3167 /* otherwise see if there are any links from this table to the obj. */
3168 //print_r($this->links());
3169 if (($ofield === false) && ($links = $this->links())) {
3170 foreach ($links as $k => $v) {
3171 /* link contains {this column} = {linked table}:{linked column} */
3172 $ar = explode(':', $v);
3173 // Feature Request #4266 - Allow joins with multiple keys
3174 if (strpos($k, ',') !== false) {
3175 $k = explode(',', $k);
3177 if (strpos($ar[1], ',') !== false) {
3178 $ar[1] = explode(',', $ar[1]);
3181 if ($ar[0] == $obj->__table) {
3182 if ($joinCol !== false) {
3183 if ($k == $joinCol) {
3198 // finally if these two table have column names that match do a join by default on them
3200 if (($ofield === false) && $joinCol) {
3205 /* did I find a conneciton between them? */
3207 if ($ofield === false) {
3209 "joinAdd: {$obj->__table} has no link with {$this->__table}",
3210 DB_DATAOBJECT_ERROR_NODATA);
3213 $joinType = strtoupper($joinType);
3215 // we default to joining as the same name (this is remvoed later..)
3217 if ($joinAs === false) {
3218 $joinAs = $obj->__table;
3221 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
3222 $options = $_DB_DATAOBJECT['CONFIG'];
3224 // not sure how portable adding database prefixes is..
3225 $objTable = $quoteIdentifiers ?
3226 $DB->quoteIdentifier($obj->__table) :
3230 if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
3231 $dbPrefix = ($quoteIdentifiers
3232 ? $DB->quoteIdentifier($obj->_database)
3233 : $obj->_database) . '.';
3236 // if they are the same, then dont add a prefix...
3237 if ($obj->_database == $this->_database) {
3240 // as far as we know only mysql supports database prefixes..
3241 // prefixing the database name is now the default behaviour,
3242 // as it enables joining mutiple columns from multiple databases...
3244 // prefix database (quoted if neccessary..)
3245 $objTable = $dbPrefix . $objTable;
3249 // if obj only a dataobject - eg. no extended class has been defined..
3250 // it obvioulsy cant work out what child elements might exist...
3251 // until we get on the fly querying of tables..
3252 // note: we have already checked that it is_a(db_dataobject earlier)
3253 if ( strtolower(get_class($obj)) != 'db_dataobject') {
3255 // now add where conditions for anything that is set in the object
3259 $items = $obj->table();
3260 // will return an array if no items..
3262 // only fail if we where expecting it to work (eg. not joined on a array)
3266 "joinAdd: No table definition for {$obj->__table}",
3267 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3271 foreach($items as $k => $v) {
3272 if (!isset($obj->$k)) {
3276 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
3279 if ($v & DB_DATAOBJECT_STR) {
3280 $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
3281 ($v & DB_DATAOBJECT_BOOL) ?
3282 // this is thanks to the braindead idea of postgres to
3283 // use t/f for boolean.
3284 (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
3289 if (is_numeric($obj->$k)) {
3290 $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
3294 if (is_a($obj->$k,'DB_DataObject_Cast')) {
3295 $value = $obj->$k->toString($v,$DB);
3296 if (PEAR::isError($value)) {
3297 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
3300 if (!isset($options['disable_null_strings']) && strtolower($value) === 'null') {
3301 $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
3304 $obj->whereAdd("{$joinAs}.{$kSql} = $value");
3310 /* this is probably an error condition! */
3311 $obj->whereAdd("{$joinAs}.{$kSql} = 0");
3313 if ($this->_query === false) {
3315 "joinAdd can not be run from a object that has had a query run on it,
3316 clone the object or create a new one and use setFrom()",
3317 DB_DATAOBJECT_ERROR_INVALIDARGS);
3322 // and finally merge the whereAdd from the child..
3323 if ($obj->_query['condition']) {
3324 $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
3326 if (!$useWhereAsOn) {
3327 $this->whereAdd($cond);
3334 // nested (join of joined objects..)
3337 // postgres allows nested queries, with ()'s
3338 // not sure what the results are with other databases..
3339 // may be unpredictable..
3340 if (in_array($DB->dsn["phptype"],array('pgsql'))) {
3341 $objTable = "($objTable {$obj->_join})";
3343 $appendJoin = $obj->_join;
3349 // add the joinee object's conditions to the ON clause instead of the WHERE clause
3350 if ($useWhereAsOn && strlen($cond)) {
3351 $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
3356 $table = $this->__table;
3358 if ($quoteIdentifiers) {
3359 $joinAs = $DB->quoteIdentifier($joinAs);
3360 $table = $DB->quoteIdentifier($table);
3361 $ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
3362 $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
3364 // add database prefix if they are different databases
3368 $addJoinAs = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->__table) : $obj->__table) != $joinAs;
3370 // join table a AS b - is only supported by a few databases and is probably not needed
3371 // , however since it makes the whole Statement alot clearer we are leaving it in
3372 // for those databases.
3373 $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
3376 $joinAs = $dbPrefix . $joinAs;
3380 switch ($joinType) {
3383 case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
3385 // Feature Request #4266 - Allow joins with multiple keys
3386 $this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3387 if (is_array($ofield)) {
3388 $key_count = count($ofield);
3389 for($i = 0; $i < $key_count; $i++) {
3391 $this->_join .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
3394 $this->_join .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
3397 $this->_join .= ' ' . $appendJoin . ' ';
3399 $this->_join .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
3404 case '': // this is just a standard multitable select..
3405 $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
3406 $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
3415 * Copies items that are in the table definitions from an
3416 * array or object into the current object
3417 * will not override key values.
3420 * @param array | object $from
3421 * @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
3422 * @param boolean $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
3424 * @return true on success or array of key=>setValue error message
3426 function setFrom($from, $format = '%s', $skipEmpty=false)
3428 global $_DB_DATAOBJECT;
3429 $keys = $this->keys();
3430 $items = $this->table();
3433 "setFrom:Could not find table definition for {$this->__table}",
3434 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3437 $overload_return = array();
3438 foreach (array_keys($items) as $k) {
3439 if (in_array($k,$keys)) {
3440 continue; // dont overwrite keys
3443 continue; // ignore empty keys!!! what
3445 if (is_object($from) && isset($from->{sprintf($format,$k)})) {
3446 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3447 if (method_exists($this,'set'.$kk)) {
3448 $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
3449 if (is_string($ret)) {
3450 $overload_return[$k] = $ret;
3454 $this->$k = $from->{sprintf($format,$k)};
3458 if (is_object($from)) {
3462 if (empty($from[$k]) && $skipEmpty) {
3466 if (!isset($from[sprintf($format,$k)])) {
3470 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3471 if (method_exists($this,'set'. $kk)) {
3472 $ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
3473 if (is_string($ret)) {
3474 $overload_return[$k] = $ret;
3478 if (is_object($from[sprintf($format,$k)])) {
3481 if (is_array($from[sprintf($format,$k)])) {
3484 $ret = $this->fromValue($k,$from[sprintf($format,$k)]);
3485 if ($ret !== true) {
3486 $overload_return[$k] = 'Not A Valid Value';
3488 //$this->$k = $from[sprintf($format,$k)];
3490 if ($overload_return) {
3491 return $overload_return;
3497 * Returns an associative array from the current data
3498 * (kind of oblivates the idea behind DataObjects, but
3499 * is usefull if you use it with things like QuickForms.
3501 * you can use the format to return things like user[key]
3502 * by sending it $object->toArray('user[%s]')
3504 * will also return links converted to arrays.
3506 * @param string sprintf format for array
3507 * @param bool empty only return elemnts that have a value set.
3510 * @return array of key => value for row
3513 function toArray($format = '%s', $hideEmpty = false)
3515 global $_DB_DATAOBJECT;
3517 $rf = ($this->_resultFields !== false) ? $this->_resultFields :
3518 (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ? $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
3519 $ar = ($rf !== false) ?
3520 array_merge($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid],$this->table()) :
3523 foreach($ar as $k=>$v) {
3525 if (!isset($this->$k)) {
3527 $ret[sprintf($format,$k)] = '';
3531 // call the overloaded getXXXX() method. - except getLink and getLinks
3532 if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
3533 $ret[sprintf($format,$k)] = $this->{'get'.$k}();
3536 // should this call toValue() ???
3537 $ret[sprintf($format,$k)] = $this->$k;
3539 if (!$this->_link_loaded) {
3542 foreach($this->_link_loaded as $k) {
3543 $ret[sprintf($format,$k)] = $this->$k->toArray();
3551 * validate the values of the object (usually prior to inserting/updating..)
3553 * Note: This was always intended as a simple validation routine.
3554 * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
3556 * This should be moved to another class: DB_DataObject_Validate
3557 * FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
3560 * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
3563 * - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
3564 * - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
3565 * These methods should return
3566 * true = everything ok
3567 * false|object = something is wrong!
3569 * - This method loads and uses the PEAR Validate Class.
3573 * @return array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
3577 global $_DB_DATAOBJECT;
3578 require_once 'Validate.php';
3579 $table = $this->table();
3581 $seq = $this->sequenceKey();
3582 $options = $_DB_DATAOBJECT['CONFIG'];
3583 foreach($table as $key => $val) {
3586 // call user defined validation always...
3587 $method = "Validate" . ucfirst($key);
3588 if (method_exists($this, $method)) {
3589 $ret[$key] = $this->$method();
3593 // if not null - and it's not set.......
3595 if (!isset($this->$key) && ($val & DB_DATAOBJECT_NOTNULL)) {
3596 // dont check empty sequence key values..
3597 if (($key == $seq[0]) && ($seq[1] == true)) {
3605 if (!isset($options['disable_null_strings']) && is_string($this->$key) && (strtolower($this->$key) == 'null')) {
3606 if ($val & DB_DATAOBJECT_NOTNULL) {
3607 $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
3614 // ignore things that are not set. ?
3616 if (!isset($this->$key)) {
3620 // if the string is empty.. assume it is ok..
3621 if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
3625 // dont try and validate cast objects - assume they are problably ok..
3626 if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
3629 // at this point if you have set something to an object, and it's not expected
3630 // the Validate will probably break!!... - rightly so! (your design is broken,
3631 // so issuing a runtime error like PEAR_Error is probably not appropriate..
3634 // todo: date time.....
3635 case ($val & DB_DATAOBJECT_STR):
3636 $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
3638 case ($val & DB_DATAOBJECT_INT):
3639 $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
3643 // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
3644 foreach ($ret as $key => $val) {
3645 if ($val !== true) {
3649 return true; // everything is OK.
3653 * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
3656 * @return object The DB connection
3658 function &getDatabaseConnection()
3660 global $_DB_DATAOBJECT;
3662 if (($e = $this->_connect()) !== true) {
3665 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
3669 return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3674 * Gets the DB result object related to the objects active query
3675 * - so you can use funky pear stuff with it - like pager for example.. :)
3678 * @return object The DB result object
3681 function &getDatabaseResult()
3683 global $_DB_DATAOBJECT;
3685 if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
3689 return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
3693 * Overload Extension support
3694 * - enables setCOLNAME/getCOLNAME
3695 * if you define a set/get method for the item it will be called.
3696 * otherwise it will just return/set the value.
3697 * NOTE this currently means that a few Names are NO-NO's
3698 * eg. links,link,linksarray, from, Databaseconnection,databaseresult
3701 * - set is automatically called by setFrom.
3702 * - get is automatically called by toArray()
3704 * setters return true on success. = strings on failure
3705 * getters return the value!
3707 * this fires off trigger_error - if any problems.. pear_error,
3708 * has problems with 4.3.2RC2 here
3716 function _call($method,$params,&$return) {
3718 //$this->debug("ATTEMPTING OVERLOAD? $method");
3719 // ignore constructors : - mm
3720 if (strtolower($method) == strtolower(get_class($this))) {
3723 $type = strtolower(substr($method,0,3));
3724 $class = get_class($this);
3725 if (($type != 'set') && ($type != 'get')) {
3731 // deal with naming conflick of setFrom = this is messy ATM!
3733 if (strtolower($method) == 'set_from') {
3734 $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
3738 $element = substr($method,3);
3740 // dont you just love php's case insensitivity!!!!
3742 $array = array_keys(get_class_vars($class));
3743 /* php5 version which segfaults on 5.0.3 */
3744 if (class_exists('ReflectionClass')) {
3745 $reflection = new ReflectionClass($class);
3746 $array = array_keys($reflection->getdefaultProperties());
3749 if (!in_array($element,$array)) {
3751 foreach($array as $k) {
3752 $case[strtolower($k)] = $k;
3754 if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
3755 trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
3756 $element = strtolower($element);
3759 // does it really exist?
3760 if (!isset($case[$element])) {
3763 // use the mundged case
3764 $element = $case[$element]; // real case !
3768 if ($type == 'get') {
3769 $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
3774 $return = $this->fromValue($element, $params[0]);
3783 * standard set* implementation.
3785 * takes data and uses it to set dates/strings etc.
3786 * normally called from __call..
3789 * date = using (standard time format, or unixtimestamp).... so you could create a method :
3790 * function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
3792 * time = using strtotime
3793 * datetime = using same as date - accepts iso standard or unixtimestamp.
3794 * string = typecast only..
3796 * TODO: add formater:: eg. d/m/Y for date! ???
3798 * @param string column of database
3799 * @param mixed value to assign
3801 * @return true| false (False on error)
3803 * @see DB_DataObject::_call
3807 function fromValue($col,$value)
3809 global $_DB_DATAOBJECT;
3810 $options = $_DB_DATAOBJECT['CONFIG'];
3811 $cols = $this->table();
3812 // dont know anything about this col..
3813 if (!isset($cols[$col])) {
3814 $this->$col = $value;
3817 //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
3819 // set to null and column is can be null...
3820 case (!isset($options['disable_null_strings']) && (strtolower($value) == 'null') && (!($cols[$col] & DB_DATAOBJECT_NOTNULL))):
3821 case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
3822 $this->$col = $value;
3825 // fail on setting null on a not null field..
3826 case (!isset($options['disable_null_strings']) && (strtolower($value) == 'null') && ($cols[$col] & DB_DATAOBJECT_NOTNULL)):
3829 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
3830 // empty values get set to '' (which is inserted/updated as NULl
3835 if (is_numeric($value)) {
3836 $this->$col = date('Y-m-d H:i:s', $value);
3840 // eak... - no way to validate date time otherwise...
3841 $this->$col = (string) $value;
3844 case ($cols[$col] & DB_DATAOBJECT_DATE):
3845 // empty values get set to '' (which is inserted/updated as NULl
3852 if (is_numeric($value)) {
3853 $this->$col = date('Y-m-d',$value);
3858 require_once 'Date.php';
3859 $x = new Date($value);
3860 $this->$col = $x->format("%Y-%m-%d");
3863 case ($cols[$col] & DB_DATAOBJECT_TIME):
3864 // empty values get set to '' (which is inserted/updated as NULl
3869 $guess = strtotime($value);
3871 $this->$col = date('H:i:s', $guess);
3872 return $return = true;
3874 // otherwise an error in type...
3877 case ($cols[$col] & DB_DATAOBJECT_STR):
3879 $this->$col = (string) $value;
3882 // todo : floats numerics and ints...
3884 $this->$col = $value;
3892 * standard get* implementation.
3895 * supported formaters:
3896 * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
3897 * numbers : %02d (eg. sprintf)
3898 * NOTE you will get unexpected results with times like 0000-00-00 !!!
3902 * @param string column of database
3903 * @param format foramt
3905 * @return true Description
3907 * @see DB_DataObject::_call(),strftime(),Date::format()
3909 function toValue($col,$format = null)
3911 if (is_null($format)) {
3914 $cols = $this->table();
3916 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
3920 $guess = strtotime($this->$col);
3922 return strftime($format, $guess);
3924 // eak... - no way to validate date time otherwise...
3926 case ($cols[$col] & DB_DATAOBJECT_DATE):
3930 $guess = strtotime($this->$col);
3932 return strftime($format,$guess);
3935 require_once 'Date.php';
3936 $x = new Date($this->$col);
3937 return $x->format($format);
3939 case ($cols[$col] & DB_DATAOBJECT_TIME):
3943 $guess = strtotime($this->$col);
3945 return strftime($format, $guess);
3947 // otherwise an error in type...
3950 case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
3954 require_once 'Date.php';
3956 $x = new Date($this->$col);
3958 return $x->format($format);
3961 case ($cols[$col] & DB_DATAOBJECT_BOOL):
3963 if ($cols[$col] & DB_DATAOBJECT_STR) {
3965 return ($this->$col === 't');
3967 return (bool) $this->$col;
3971 return sprintf($format,$this->col);
3978 /* ----------------------- Debugger ------------------ */
3981 * Debugger. - use this in your extended classes to output debugging information.
3983 * Uses DB_DataObject::DebugLevel(x) to turn it on
3985 * @param string $message - message to output
3986 * @param string $logtype - bold at start
3987 * @param string $level - output level
3991 function debug($message, $logtype = 0, $level = 1)
3993 global $_DB_DATAOBJECT;
3995 if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
3996 (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
3999 // this is a bit flaky due to php's wonderfull class passing around crap..
4000 // but it's about as good as it gets..
4001 $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
4003 if (!is_string($message)) {
4004 $message = print_r($message,true);
4006 if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
4007 return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
4010 if (!ini_get('html_errors')) {
4011 echo "$class : $logtype : $message\n";
4015 if (!is_string($message)) {
4016 $message = print_r($message,true);
4018 $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
4019 echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
4023 * sets and returns debug level
4024 * eg. DB_DataObject::debugLevel(4);
4026 * @param int $v level
4030 function debugLevel($v = null)
4032 global $_DB_DATAOBJECT;
4033 if (empty($_DB_DATAOBJECT['CONFIG'])) {
4034 DB_DataObject::_loadConfig();
4037 $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4038 $_DB_DATAOBJECT['CONFIG']['debug'] = $v;
4041 return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4045 * Last Error that has occured
4046 * - use $this->_lastError or
4047 * $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4050 * @var object PEAR_Error (or false)
4052 var $_lastError = false;
4055 * Default error handling is to create a pear error, but never return it.
4056 * if you need to handle errors you should look at setting the PEAR_Error callback
4057 * this is due to the fact it would wreck havoc on the internal methods!
4059 * @param int $message message
4060 * @param int $type type
4061 * @param int $behaviour behaviour (die or continue!);
4063 * @return error object
4065 function raiseError($message, $type = null, $behaviour = null)
4067 global $_DB_DATAOBJECT;
4069 if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
4072 $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4074 // this will never work totally with PHP's object model.
4075 // as this is passed on static calls (like staticGet in our case)
4077 if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
4078 $this->_lastError = $error;
4081 $_DB_DATAOBJECT['LASTERROR'] = $error;
4083 // no checks for production here?....... - we log errors before we throw them.
4084 DB_DataObject::debug($message,'ERROR',1);
4087 if (PEAR::isError($message)) {
4090 require_once 'DB/DataObject/Error.php';
4091 $error = PEAR::raiseError($message, $type, $behaviour,
4092 $opts=null, $userinfo=null, 'DB_DataObject_Error'
4100 * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
4102 * After Profiling DB_DataObject, I discoved that the debug calls where taking
4103 * considerable time (well 0.1 ms), so this should stop those calls happening. as
4104 * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
4105 * THIS STILL NEEDS FURTHER INVESTIGATION
4108 * @return object an error object
4110 function _loadConfig()
4112 global $_DB_DATAOBJECT;
4114 $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
4119 * Free global arrays associated with this object.
4127 global $_DB_DATAOBJECT;
4129 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
4130 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
4132 if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4133 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
4135 // clear the staticGet cache as well.
4136 $this->_clear_cache();
4137 // this is a huge bug in DB!
4138 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4139 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
4145 /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
4147 function _get_table() { return $this->table(); }
4148 function _get_keys() { return $this->keys(); }
4154 // technially 4.3.2RC1 was broken!!
4155 // looks like 4.3.3 may have problems too....
4156 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
4158 if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
4159 if (version_compare( phpversion(), "5") < 0) {
4160 overload('DB_DataObject');
4162 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;