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];
2361 if ($_DB_driver == 'DB') {
2362 $result = $DB->query($string);
2364 switch (strtolower(substr(trim($string),0,6))) {
2369 $result = $DB->exec($string);
2373 $result = $DB->query($string);
2380 if (is_a($result,'PEAR_Error')) {
2381 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2382 $this->debug($result->toString(), "Query Error",1 );
2384 return $this->raiseError($result);
2386 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2387 $t= explode(' ',microtime());
2388 $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
2389 $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query',1);
2391 switch (strtolower(substr(trim($string),0,6))) {
2395 if ($_DB_driver == 'DB') {
2397 return $DB->affectedRows();
2401 if (is_object($result)) {
2402 // lets hope that copying the result object is OK!
2404 $_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
2405 $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
2406 $this->_DB_resultid = $_DB_resultid;
2409 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2410 $this->debug(serialize($result), 'RESULT',5);
2412 if (method_exists($result, 'numrows')) {
2413 if ($_DB_driver == 'DB') {
2414 $DB->expectError(DB_ERROR_UNSUPPORTED);
2416 $DB->expectError(MDB2_ERROR_UNSUPPORTED);
2418 $this->N = $result->numrows();
2419 if (is_a($this->N,'PEAR_Error')) {
2427 * Builds the WHERE based on the values of of this object
2429 * @param mixed $keys
2430 * @param array $filter (used by update to only uses keys in this filter list).
2431 * @param array $negative_filter (used by delete to prevent deleting using the keys mentioned..)
2435 function _build_condition($keys, $filter = array(),$negative_filter=array())
2437 global $_DB_DATAOBJECT;
2439 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2441 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
2442 $options = $_DB_DATAOBJECT['CONFIG'];
2444 // if we dont have query vars.. - reset them.
2445 if ($this->_query === false) {
2446 $x = new DB_DataObject;
2447 $this->_query= $x->_query;
2450 foreach($keys as $k => $v) {
2451 // index keys is an indexed array
2452 /* these filter checks are a bit suspicious..
2453 - need to check that update really wants to work this way */
2456 if (!in_array($k, $filter)) {
2460 if ($negative_filter) {
2461 if (in_array($k, $negative_filter)) {
2465 if (!isset($this->$k)) {
2469 $kSql = $quoteIdentifiers
2470 ? ( $DB->quoteIdentifier($this->__table) . '.' . $DB->quoteIdentifier($k) )
2471 : "{$this->__table}.{$k}";
2475 if (is_a($this->$k,'DB_DataObject_Cast')) {
2476 $dbtype = $DB->dsn["phptype"];
2477 $value = $this->$k->toString($v,$DB);
2478 if (PEAR::isError($value)) {
2479 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
2482 if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2483 $this->whereAdd(" $kSql IS NULL");
2486 $this->whereAdd(" $kSql = $value");
2490 if (!isset($options['disable_null_strings']) && (strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2491 $this->whereAdd(" $kSql IS NULL");
2496 if ($v & DB_DATAOBJECT_STR) {
2497 $this->whereAdd(" $kSql = " . $this->_quote((string) (
2498 ($v & DB_DATAOBJECT_BOOL) ?
2499 // this is thanks to the braindead idea of postgres to
2500 // use t/f for boolean.
2501 (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
2506 if (is_numeric($this->$k)) {
2507 $this->whereAdd(" $kSql = {$this->$k}");
2510 /* this is probably an error condition! */
2511 $this->whereAdd(" $kSql = ".intval($this->$k));
2516 * autoload Class relating to a table
2517 * (depreciated - use ::factory)
2519 * @param string $table table
2521 * @return string classname on Success
2523 function staticAutoloadTable($table)
2525 global $_DB_DATAOBJECT;
2526 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2527 DB_DataObject::_loadConfig();
2529 $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2530 $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
2531 $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2533 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2534 $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
2540 * classic factory method for loading a table class
2541 * usage: $do = DB_DataObject::factory('person')
2542 * WARNING - this may emit a include error if the file does not exist..
2543 * use @ to silence it (if you are sure it is acceptable)
2544 * eg. $do = @DB_DataObject::factory('person')
2546 * table name will eventually be databasename/table
2547 * - and allow modular dataobjects to be written..
2548 * (this also helps proxy creation)
2551 * @param string $table tablename (use blank to create a new instance of the same class.)
2553 * @return DataObject|PEAR_Error
2558 function factory($table = '') {
2559 global $_DB_DATAOBJECT;
2560 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2561 DB_DataObject::_loadConfig();
2564 if ($table === '') {
2565 if (is_a($this,'DB_DataObject') && strlen($this->__table)) {
2566 $table = $this->__table;
2568 return DB_DataObject::raiseError(
2569 "factory did not recieve a table name",
2570 DB_DATAOBJECT_ERROR_INVALIDARGS);
2575 $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2576 $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
2577 $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2579 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2580 $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
2582 // proxy = full|light
2583 if (!$class && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
2584 $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
2585 class_exists('DB_DataObject_Generator') ? '' :
2586 require_once 'DB/DataObject/Generator.php';
2588 $d = new DB_DataObject;
2590 $d->__table = $table;
2591 if (is_a($ret = $d->_connect(), 'PEAR_Error')) {
2595 $x = new DB_DataObject_Generator;
2596 return $x->$proxyMethod( $d->_database, $table);
2600 return DB_DataObject::raiseError(
2601 "factory could not find class $class from $table",
2602 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2610 * @param string $class Class
2612 * @return string classname on Success
2614 function _autoloadClass($class)
2616 global $_DB_DATAOBJECT;
2618 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2619 DB_DataObject::_loadConfig();
2621 $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2622 '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
2624 $table = substr($class,strlen($class_prefix));
2626 // only include the file if it exists - and barf badly if it has parse errors :)
2627 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
2632 if (strpos($_DB_DATAOBJECT['CONFIG']['class_location'],'%s') !== false) {
2633 $file = sprintf($_DB_DATAOBJECT['CONFIG']['class_location'], preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
2635 $file = $_DB_DATAOBJECT['CONFIG']['class_location'].'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2638 if (!file_exists($file)) {
2640 foreach(explode(PATH_SEPARATOR, ini_get('include_path')) as $p) {
2641 if (file_exists("$p/$file")) {
2648 DB_DataObject::raiseError(
2649 "autoload:Could not find class {$class} using class_location value",
2650 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2658 $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2661 DB_DataObject::raiseError(
2662 "autoload:Could not autoload {$class}",
2663 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2672 * Have the links been loaded?
2673 * if they have it contains a array of those variables.
2676 * @var boolean | array
2678 var $_link_loaded = false;
2681 * Get the links associate array as defined by the links.ini file.
2685 * Should look a bit like
2686 * [local_col_name] => "related_tablename:related_col_name"
2689 * @return array|null
2690 * array = if there are links defined for this table.
2691 * empty array - if there is a links.ini file, but no links on this table
2692 * null - if no links.ini exists for this database (hence try auto_links).
2694 * @see DB_DataObject::getLinks(), DB_DataObject::getLink()
2699 global $_DB_DATAOBJECT;
2700 if (empty($_DB_DATAOBJECT['CONFIG'])) {
2701 $this->_loadConfig();
2703 // have to connect.. -> otherwise things break later.
2706 if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
2707 return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
2714 // attempt to load links file here..
2716 if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
2717 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
2718 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
2721 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
2722 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
2723 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
2724 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
2729 foreach ($schemas as $ini) {
2732 isset($_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"]) ?
2733 $_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"] :
2734 str_replace('.ini','.links.ini',$ini);
2736 if (empty($_DB_DATAOBJECT['LINKS'][$this->_database]) && file_exists($links) && is_file($links)) {
2737 /* not sure why $links = ... here - TODO check if that works */
2738 $_DB_DATAOBJECT['LINKS'][$this->_database] = parse_ini_file($links, true);
2739 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2740 $this->debug("Loaded links.ini file: $links","links",1);
2743 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2744 $this->debug("Missing links.ini file: $links","links",1);
2751 // if there is no link data at all on the file!
2753 if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
2757 if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
2758 return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
2764 * load related objects
2766 * There are two ways to use this, one is to set up a <dbname>.links.ini file
2767 * into a static property named <dbname>.links and specifies the table joins,
2768 * the other highly dependent on naming columns 'correctly' :)
2769 * using colname = xxxxx_yyyyyy
2770 * xxxxxx = related table; (yyyyy = user defined..)
2771 * looks up table xxxxx, for value id=$this->xxxxx
2772 * stores it in $this->_xxxxx_yyyyy
2773 * you can change what object vars the links are stored in by
2774 * changeing the format parameter
2777 * @param string format (default _%s) where %s is the table name.
2778 * @author Tim White <tim@cyface.com>
2780 * @return boolean , true on success
2782 function getLinks($format = '_%s')
2785 // get table will load the options.
2786 if ($this->_link_loaded) {
2789 $this->_link_loaded = false;
2790 $cols = $this->table();
2791 $links = $this->links();
2796 foreach($links as $key => $match) {
2797 list($table,$link) = explode(':', $match);
2798 $k = sprintf($format, str_replace('.', '_', $key));
2799 // makes sure that '.' is the end of the key;
2800 if ($p = strpos($key,'.')) {
2801 $key = substr($key, 0, $p);
2804 $this->$k = $this->getLink($key, $table, $link);
2806 if (is_object($this->$k)) {
2810 $this->_link_loaded = $loaded;
2813 // this is the autonaming stuff..
2814 // it sends the column name down to getLink and lets that sort it out..
2815 // if there is a links file then it is not used!
2816 // IT IS DEPRECIATED!!!! - USE
2817 if (!is_null($links)) {
2822 foreach (array_keys($cols) as $key) {
2823 if (!($p = strpos($key, '_'))) {
2826 // does the table exist.
2827 $k =sprintf($format, $key);
2828 $this->$k = $this->getLink($key);
2829 if (is_object($this->$k)) {
2833 $this->_link_loaded = $loaded;
2838 * return name from related object
2840 * There are two ways to use this, one is to set up a <dbname>.links.ini file
2841 * into a static property named <dbname>.links and specifies the table joins,
2842 * the other is highly dependant on naming columns 'correctly' :)
2844 * NOTE: the naming convention is depreciated!!! - use links.ini
2846 * using colname = xxxxx_yyyyyy
2847 * xxxxxx = related table; (yyyyy = user defined..)
2848 * looks up table xxxxx, for value id=$this->xxxxx
2849 * stores it in $this->_xxxxx_yyyyy
2851 * you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
2854 * @param string $row either row or row.xxxxx
2855 * @param string $table name of table to look up value in
2856 * @param string $link name of column in other table to match
2857 * @author Tim White <tim@cyface.com>
2859 * @return mixed object on success
2861 function getLink($row, $table = null, $link = false)
2865 // GUESS THE LINKED TABLE.. (if found - recursevly call self)
2867 if ($table === null) {
2868 $links = $this->links();
2870 if (is_array($links)) {
2873 list($table,$link) = explode(':', $links[$row]);
2874 if ($p = strpos($row,".")) {
2875 $row = substr($row,0,$p);
2877 return $this->getLink($row,$table,$link);
2882 "getLink: $row is not defined as a link (normally this is ok)",
2883 DB_DATAOBJECT_ERROR_NODATA);
2886 return $r;// technically a possible error condition?
2889 // use the old _ method - this shouldnt happen if called via getLinks()
2890 if (!($p = strpos($row, '_'))) {
2894 $table = substr($row, 0, $p);
2895 return $this->getLink($row, $table);
2902 if (!isset($this->$row)) {
2903 $this->raiseError("getLink: row not set $row", DB_DATAOBJECT_ERROR_NODATA);
2907 // check to see if we know anything about this table..
2909 $obj = $this->factory($table);
2911 if (!is_a($obj,'DB_DataObject')) {
2913 "getLink:Could not find class for row $row, table $table",
2914 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2918 if ($obj->get($link, $this->$row)) {
2925 if ($obj->get($this->$row)) {
2934 * IS THIS SUPPORTED/USED ANYMORE????
2935 *return a list of options for a linked table
2937 * This is highly dependant on naming columns 'correctly' :)
2938 * using colname = xxxxx_yyyyyy
2939 * xxxxxx = related table; (yyyyy = user defined..)
2940 * looks up table xxxxx, for value id=$this->xxxxx
2941 * stores it in $this->_xxxxx_yyyyy
2944 * @return array of results (empty array on failure)
2946 function &getLinkArray($row, $table = null)
2951 $links = $this->links();
2953 if (is_array($links)) {
2954 if (!isset($links[$row])) {
2958 list($table,$link) = explode(':',$links[$row]);
2960 if (!($p = strpos($row,'_'))) {
2963 $table = substr($row,0,$p);
2967 $c = $this->factory($table);
2969 if (!is_a($c,'DB_DataObject')) {
2971 "getLinkArray:Could not find class for row $row, table $table",
2972 DB_DATAOBJECT_ERROR_INVALIDCONFIG
2977 // if the user defined method list exists - use it...
2978 if (method_exists($c, 'listFind')) {
2979 $c->listFind($this->id);
2983 while ($c->fetch()) {
2990 * The JOIN condition
2998 * joinAdd - adds another dataobject to this, building a joined query.
3000 * example (requires links.ini to be set up correctly)
3001 * // get all the images for product 24
3002 * $i = new DataObject_Image();
3003 * $pi = new DataObjects_Product_image();
3004 * $pi->product_id = 24; // set the product id to 24
3005 * $i->joinAdd($pi); // add the product_image connectoin
3007 * while ($i->fetch()) {
3010 * // an example with 2 joins
3011 * // get all the images linked with products or productgroups
3012 * $i = new DataObject_Image();
3013 * $pi = new DataObject_Product_image();
3014 * $pgi = new DataObject_Productgroup_image();
3016 * $i->joinAdd($pgi);
3018 * while ($i->fetch()) {
3023 * @param optional $obj object |array the joining object (no value resets the join)
3024 * If you use an array here it should be in the format:
3025 * array('local_column','remotetable:remote_column');
3026 * if remotetable does not have a definition, you should
3027 * use @ to hide the include error message..
3030 * @param optional $joinType string | array
3031 * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
3032 * just select ... from a,b,c with no join and
3033 * links are added as where items.
3035 * If second Argument is array, it is assumed to be an associative
3036 * array with arguments matching below = eg.
3037 * 'joinType' => 'INNER',
3040 * 'useWhereAsOn' => false,
3042 * @param optional $joinAs string if you want to select the table as anther name
3043 * useful when you want to select multiple columsn
3044 * from a secondary table.
3046 * @param optional $joinCol string The column on This objects table to match (needed
3047 * if this table links to the child object in
3048 * multiple places eg.
3049 * user->friend (is a link to another user)
3050 * user->mother (is a link to another user..)
3052 * optional 'useWhereAsOn' bool default false;
3053 * convert the where argments from the object being added
3054 * into ON arguments.
3059 * @author Stijn de Reede <sjr@gmx.co.uk>
3061 function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
3063 global $_DB_DATAOBJECT;
3064 if ($obj === false) {
3070 $useWhereAsOn = false;
3071 // support for 2nd argument as an array of options
3072 if (is_array($joinType)) {
3073 // new options can now go in here... (dont forget to document them)
3074 $useWhereAsOn = !empty($joinType['useWhereAsOn']);
3075 $joinCol = isset($joinType['joinCol']) ? $joinType['joinCol'] : $joinCol;
3076 $joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
3077 $joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
3079 // support for array as first argument
3080 // this assumes that you dont have a links.ini for the specified table.
3081 // and it doesnt exist as am extended dataobject!! - experimental.
3083 $ofield = false; // object field
3084 $tfield = false; // this field
3086 if (is_array($obj)) {
3088 list($toTable,$ofield) = explode(':',$obj[1]);
3089 $obj = DB_DataObject::factory($toTable);
3091 if (!$obj || is_a($obj,'PEAR_Error')) {
3092 $obj = new DB_DataObject;
3093 $obj->__table = $toTable;
3096 // set the table items to nothing.. - eg. do not try and match
3097 // things in the child table...???
3101 if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
3102 return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
3104 /* make sure $this->_database is set. */
3106 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3111 /* look up the links for obj table */
3112 //print_r($obj->links());
3113 if (!$ofield && ($olinks = $obj->links())) {
3115 foreach ($olinks as $k => $v) {
3116 /* link contains {this column} = {linked table}:{linked column} */
3117 $ar = explode(':', $v);
3119 // Feature Request #4266 - Allow joins with multiple keys
3121 $links_key_array = strpos($k,',');
3122 if ($links_key_array !== false) {
3123 $k = explode(',', $k);
3126 $ar_array = strpos($ar[1],',');
3127 if ($ar_array !== false) {
3128 $ar[1] = explode(',', $ar[1]);
3131 if ($ar[0] == $this->__table) {
3133 // you have explictly specified the column
3134 // and the col is listed here..
3135 // not sure if 1:1 table could cause probs here..
3137 if ($joinCol !== false) {
3139 "joinAdd: You cannot target a join column in the " .
3140 "'link from' table ({$obj->__table}). " .
3141 "Either remove the fourth argument to joinAdd() ".
3142 "({$joinCol}), or alter your links.ini file.",
3143 DB_DATAOBJECT_ERROR_NODATA);
3154 /* otherwise see if there are any links from this table to the obj. */
3155 //print_r($this->links());
3156 if (($ofield === false) && ($links = $this->links())) {
3157 foreach ($links as $k => $v) {
3158 /* link contains {this column} = {linked table}:{linked column} */
3159 $ar = explode(':', $v);
3160 // Feature Request #4266 - Allow joins with multiple keys
3161 if (strpos($k, ',') !== false) {
3162 $k = explode(',', $k);
3164 if (strpos($ar[1], ',') !== false) {
3165 $ar[1] = explode(',', $ar[1]);
3168 if ($ar[0] == $obj->__table) {
3169 if ($joinCol !== false) {
3170 if ($k == $joinCol) {
3185 // finally if these two table have column names that match do a join by default on them
3187 if (($ofield === false) && $joinCol) {
3192 /* did I find a conneciton between them? */
3194 if ($ofield === false) {
3196 "joinAdd: {$obj->__table} has no link with {$this->__table}",
3197 DB_DATAOBJECT_ERROR_NODATA);
3200 $joinType = strtoupper($joinType);
3202 // we default to joining as the same name (this is remvoed later..)
3204 if ($joinAs === false) {
3205 $joinAs = $obj->__table;
3208 $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
3209 $options = $_DB_DATAOBJECT['CONFIG'];
3211 // not sure how portable adding database prefixes is..
3212 $objTable = $quoteIdentifiers ?
3213 $DB->quoteIdentifier($obj->__table) :
3217 if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
3218 $dbPrefix = ($quoteIdentifiers
3219 ? $DB->quoteIdentifier($obj->_database)
3220 : $obj->_database) . '.';
3223 // if they are the same, then dont add a prefix...
3224 if ($obj->_database == $this->_database) {
3227 // as far as we know only mysql supports database prefixes..
3228 // prefixing the database name is now the default behaviour,
3229 // as it enables joining mutiple columns from multiple databases...
3231 // prefix database (quoted if neccessary..)
3232 $objTable = $dbPrefix . $objTable;
3236 // if obj only a dataobject - eg. no extended class has been defined..
3237 // it obvioulsy cant work out what child elements might exist...
3238 // until we get on the fly querying of tables..
3239 // note: we have already checked that it is_a(db_dataobject earlier)
3240 if ( strtolower(get_class($obj)) != 'db_dataobject') {
3242 // now add where conditions for anything that is set in the object
3246 $items = $obj->table();
3247 // will return an array if no items..
3249 // only fail if we where expecting it to work (eg. not joined on a array)
3253 "joinAdd: No table definition for {$obj->__table}",
3254 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3258 foreach($items as $k => $v) {
3259 if (!isset($obj->$k)) {
3263 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
3266 if ($v & DB_DATAOBJECT_STR) {
3267 $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
3268 ($v & DB_DATAOBJECT_BOOL) ?
3269 // this is thanks to the braindead idea of postgres to
3270 // use t/f for boolean.
3271 (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
3276 if (is_numeric($obj->$k)) {
3277 $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
3281 if (is_a($obj->$k,'DB_DataObject_Cast')) {
3282 $value = $obj->$k->toString($v,$DB);
3283 if (PEAR::isError($value)) {
3284 $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
3287 if (!isset($options['disable_null_strings']) && strtolower($value) === 'null') {
3288 $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
3291 $obj->whereAdd("{$joinAs}.{$kSql} = $value");
3297 /* this is probably an error condition! */
3298 $obj->whereAdd("{$joinAs}.{$kSql} = 0");
3300 if ($this->_query === false) {
3302 "joinAdd can not be run from a object that has had a query run on it,
3303 clone the object or create a new one and use setFrom()",
3304 DB_DATAOBJECT_ERROR_INVALIDARGS);
3309 // and finally merge the whereAdd from the child..
3310 if ($obj->_query['condition']) {
3311 $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
3313 if (!$useWhereAsOn) {
3314 $this->whereAdd($cond);
3321 // nested (join of joined objects..)
3324 // postgres allows nested queries, with ()'s
3325 // not sure what the results are with other databases..
3326 // may be unpredictable..
3327 if (in_array($DB->dsn["phptype"],array('pgsql'))) {
3328 $objTable = "($objTable {$obj->_join})";
3330 $appendJoin = $obj->_join;
3336 // add the joinee object's conditions to the ON clause instead of the WHERE clause
3337 if ($useWhereAsOn && strlen($cond)) {
3338 $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
3343 $table = $this->__table;
3345 if ($quoteIdentifiers) {
3346 $joinAs = $DB->quoteIdentifier($joinAs);
3347 $table = $DB->quoteIdentifier($table);
3348 $ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
3349 $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
3351 // add database prefix if they are different databases
3355 $addJoinAs = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->__table) : $obj->__table) != $joinAs;
3357 // join table a AS b - is only supported by a few databases and is probably not needed
3358 // , however since it makes the whole Statement alot clearer we are leaving it in
3359 // for those databases.
3360 $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
3363 $joinAs = $dbPrefix . $joinAs;
3367 switch ($joinType) {
3370 case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
3372 // Feature Request #4266 - Allow joins with multiple keys
3373 $this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3374 if (is_array($ofield)) {
3375 $key_count = count($ofield);
3376 for($i = 0; $i < $key_count; $i++) {
3378 $this->_join .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
3381 $this->_join .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
3384 $this->_join .= ' ' . $appendJoin . ' ';
3386 $this->_join .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
3391 case '': // this is just a standard multitable select..
3392 $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
3393 $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
3402 * Copies items that are in the table definitions from an
3403 * array or object into the current object
3404 * will not override key values.
3407 * @param array | object $from
3408 * @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
3409 * @param boolean $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
3411 * @return true on success or array of key=>setValue error message
3413 function setFrom($from, $format = '%s', $skipEmpty=false)
3415 global $_DB_DATAOBJECT;
3416 $keys = $this->keys();
3417 $items = $this->table();
3420 "setFrom:Could not find table definition for {$this->__table}",
3421 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3424 $overload_return = array();
3425 foreach (array_keys($items) as $k) {
3426 if (in_array($k,$keys)) {
3427 continue; // dont overwrite keys
3430 continue; // ignore empty keys!!! what
3432 if (is_object($from) && isset($from->{sprintf($format,$k)})) {
3433 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3434 if (method_exists($this,'set'.$kk)) {
3435 $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
3436 if (is_string($ret)) {
3437 $overload_return[$k] = $ret;
3441 $this->$k = $from->{sprintf($format,$k)};
3445 if (is_object($from)) {
3449 if (empty($from[$k]) && $skipEmpty) {
3453 if (!isset($from[sprintf($format,$k)])) {
3457 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3458 if (method_exists($this,'set'. $kk)) {
3459 $ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
3460 if (is_string($ret)) {
3461 $overload_return[$k] = $ret;
3465 if (is_object($from[sprintf($format,$k)])) {
3468 if (is_array($from[sprintf($format,$k)])) {
3471 $ret = $this->fromValue($k,$from[sprintf($format,$k)]);
3472 if ($ret !== true) {
3473 $overload_return[$k] = 'Not A Valid Value';
3475 //$this->$k = $from[sprintf($format,$k)];
3477 if ($overload_return) {
3478 return $overload_return;
3484 * Returns an associative array from the current data
3485 * (kind of oblivates the idea behind DataObjects, but
3486 * is usefull if you use it with things like QuickForms.
3488 * you can use the format to return things like user[key]
3489 * by sending it $object->toArray('user[%s]')
3491 * will also return links converted to arrays.
3493 * @param string sprintf format for array
3494 * @param bool empty only return elemnts that have a value set.
3497 * @return array of key => value for row
3500 function toArray($format = '%s', $hideEmpty = false)
3502 global $_DB_DATAOBJECT;
3504 $rf = ($this->_resultFields !== false) ? $this->_resultFields :
3505 (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ? $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
3506 $ar = ($rf !== false) ?
3507 array_merge($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid],$this->table()) :
3510 foreach($ar as $k=>$v) {
3512 if (!isset($this->$k)) {
3514 $ret[sprintf($format,$k)] = '';
3518 // call the overloaded getXXXX() method. - except getLink and getLinks
3519 if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
3520 $ret[sprintf($format,$k)] = $this->{'get'.$k}();
3523 // should this call toValue() ???
3524 $ret[sprintf($format,$k)] = $this->$k;
3526 if (!$this->_link_loaded) {
3529 foreach($this->_link_loaded as $k) {
3530 $ret[sprintf($format,$k)] = $this->$k->toArray();
3538 * validate the values of the object (usually prior to inserting/updating..)
3540 * Note: This was always intended as a simple validation routine.
3541 * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
3543 * This should be moved to another class: DB_DataObject_Validate
3544 * FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
3547 * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
3550 * - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
3551 * - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
3552 * These methods should return
3553 * true = everything ok
3554 * false|object = something is wrong!
3556 * - This method loads and uses the PEAR Validate Class.
3560 * @return array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
3564 global $_DB_DATAOBJECT;
3565 require_once 'Validate.php';
3566 $table = $this->table();
3568 $seq = $this->sequenceKey();
3569 $options = $_DB_DATAOBJECT['CONFIG'];
3570 foreach($table as $key => $val) {
3573 // call user defined validation always...
3574 $method = "Validate" . ucfirst($key);
3575 if (method_exists($this, $method)) {
3576 $ret[$key] = $this->$method();
3580 // if not null - and it's not set.......
3582 if (!isset($this->$key) && ($val & DB_DATAOBJECT_NOTNULL)) {
3583 // dont check empty sequence key values..
3584 if (($key == $seq[0]) && ($seq[1] == true)) {
3592 if (!isset($options['disable_null_strings']) && is_string($this->$key) && (strtolower($this->$key) == 'null')) {
3593 if ($val & DB_DATAOBJECT_NOTNULL) {
3594 $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
3601 // ignore things that are not set. ?
3603 if (!isset($this->$key)) {
3607 // if the string is empty.. assume it is ok..
3608 if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
3612 // dont try and validate cast objects - assume they are problably ok..
3613 if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
3616 // at this point if you have set something to an object, and it's not expected
3617 // the Validate will probably break!!... - rightly so! (your design is broken,
3618 // so issuing a runtime error like PEAR_Error is probably not appropriate..
3621 // todo: date time.....
3622 case ($val & DB_DATAOBJECT_STR):
3623 $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
3625 case ($val & DB_DATAOBJECT_INT):
3626 $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
3630 // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
3631 foreach ($ret as $key => $val) {
3632 if ($val !== true) {
3636 return true; // everything is OK.
3640 * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
3643 * @return object The DB connection
3645 function &getDatabaseConnection()
3647 global $_DB_DATAOBJECT;
3649 if (($e = $this->_connect()) !== true) {
3652 if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
3656 return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3661 * Gets the DB result object related to the objects active query
3662 * - so you can use funky pear stuff with it - like pager for example.. :)
3665 * @return object The DB result object
3668 function &getDatabaseResult()
3670 global $_DB_DATAOBJECT;
3672 if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
3676 return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
3680 * Overload Extension support
3681 * - enables setCOLNAME/getCOLNAME
3682 * if you define a set/get method for the item it will be called.
3683 * otherwise it will just return/set the value.
3684 * NOTE this currently means that a few Names are NO-NO's
3685 * eg. links,link,linksarray, from, Databaseconnection,databaseresult
3688 * - set is automatically called by setFrom.
3689 * - get is automatically called by toArray()
3691 * setters return true on success. = strings on failure
3692 * getters return the value!
3694 * this fires off trigger_error - if any problems.. pear_error,
3695 * has problems with 4.3.2RC2 here
3703 function _call($method,$params,&$return) {
3705 //$this->debug("ATTEMPTING OVERLOAD? $method");
3706 // ignore constructors : - mm
3707 if (strtolower($method) == strtolower(get_class($this))) {
3710 $type = strtolower(substr($method,0,3));
3711 $class = get_class($this);
3712 if (($type != 'set') && ($type != 'get')) {
3718 // deal with naming conflick of setFrom = this is messy ATM!
3720 if (strtolower($method) == 'set_from') {
3721 $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
3725 $element = substr($method,3);
3727 // dont you just love php's case insensitivity!!!!
3729 $array = array_keys(get_class_vars($class));
3730 /* php5 version which segfaults on 5.0.3 */
3731 if (class_exists('ReflectionClass')) {
3732 $reflection = new ReflectionClass($class);
3733 $array = array_keys($reflection->getdefaultProperties());
3736 if (!in_array($element,$array)) {
3738 foreach($array as $k) {
3739 $case[strtolower($k)] = $k;
3741 if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
3742 trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
3743 $element = strtolower($element);
3746 // does it really exist?
3747 if (!isset($case[$element])) {
3750 // use the mundged case
3751 $element = $case[$element]; // real case !
3755 if ($type == 'get') {
3756 $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
3761 $return = $this->fromValue($element, $params[0]);
3770 * standard set* implementation.
3772 * takes data and uses it to set dates/strings etc.
3773 * normally called from __call..
3776 * date = using (standard time format, or unixtimestamp).... so you could create a method :
3777 * function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
3779 * time = using strtotime
3780 * datetime = using same as date - accepts iso standard or unixtimestamp.
3781 * string = typecast only..
3783 * TODO: add formater:: eg. d/m/Y for date! ???
3785 * @param string column of database
3786 * @param mixed value to assign
3788 * @return true| false (False on error)
3790 * @see DB_DataObject::_call
3794 function fromValue($col,$value)
3796 global $_DB_DATAOBJECT;
3797 $options = $_DB_DATAOBJECT['CONFIG'];
3798 $cols = $this->table();
3799 // dont know anything about this col..
3800 if (!isset($cols[$col])) {
3801 $this->$col = $value;
3804 //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
3806 // set to null and column is can be null...
3807 case (!isset($options['disable_null_strings']) && (strtolower($value) == 'null') && (!($cols[$col] & DB_DATAOBJECT_NOTNULL))):
3808 case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
3809 $this->$col = $value;
3812 // fail on setting null on a not null field..
3813 case (!isset($options['disable_null_strings']) && (strtolower($value) == 'null') && ($cols[$col] & DB_DATAOBJECT_NOTNULL)):
3816 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
3817 // empty values get set to '' (which is inserted/updated as NULl
3822 if (is_numeric($value)) {
3823 $this->$col = date('Y-m-d H:i:s', $value);
3827 // eak... - no way to validate date time otherwise...
3828 $this->$col = (string) $value;
3831 case ($cols[$col] & DB_DATAOBJECT_DATE):
3832 // empty values get set to '' (which is inserted/updated as NULl
3839 if (is_numeric($value)) {
3840 $this->$col = date('Y-m-d',$value);
3845 require_once 'Date.php';
3846 $x = new Date($value);
3847 $this->$col = $x->format("%Y-%m-%d");
3850 case ($cols[$col] & DB_DATAOBJECT_TIME):
3851 // empty values get set to '' (which is inserted/updated as NULl
3856 $guess = strtotime($value);
3858 $this->$col = date('H:i:s', $guess);
3859 return $return = true;
3861 // otherwise an error in type...
3864 case ($cols[$col] & DB_DATAOBJECT_STR):
3866 $this->$col = (string) $value;
3869 // todo : floats numerics and ints...
3871 $this->$col = $value;
3879 * standard get* implementation.
3882 * supported formaters:
3883 * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
3884 * numbers : %02d (eg. sprintf)
3885 * NOTE you will get unexpected results with times like 0000-00-00 !!!
3889 * @param string column of database
3890 * @param format foramt
3892 * @return true Description
3894 * @see DB_DataObject::_call(),strftime(),Date::format()
3896 function toValue($col,$format = null)
3898 if (is_null($format)) {
3901 $cols = $this->table();
3903 case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
3907 $guess = strtotime($this->$col);
3909 return strftime($format, $guess);
3911 // eak... - no way to validate date time otherwise...
3913 case ($cols[$col] & DB_DATAOBJECT_DATE):
3917 $guess = strtotime($this->$col);
3919 return strftime($format,$guess);
3922 require_once 'Date.php';
3923 $x = new Date($this->$col);
3924 return $x->format($format);
3926 case ($cols[$col] & DB_DATAOBJECT_TIME):
3930 $guess = strtotime($this->$col);
3932 return strftime($format, $guess);
3934 // otherwise an error in type...
3937 case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
3941 require_once 'Date.php';
3943 $x = new Date($this->$col);
3945 return $x->format($format);
3948 case ($cols[$col] & DB_DATAOBJECT_BOOL):
3950 if ($cols[$col] & DB_DATAOBJECT_STR) {
3952 return ($this->$col === 't');
3954 return (bool) $this->$col;
3958 return sprintf($format,$this->col);
3965 /* ----------------------- Debugger ------------------ */
3968 * Debugger. - use this in your extended classes to output debugging information.
3970 * Uses DB_DataObject::DebugLevel(x) to turn it on
3972 * @param string $message - message to output
3973 * @param string $logtype - bold at start
3974 * @param string $level - output level
3978 function debug($message, $logtype = 0, $level = 1)
3980 global $_DB_DATAOBJECT;
3982 if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
3983 (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
3986 // this is a bit flaky due to php's wonderfull class passing around crap..
3987 // but it's about as good as it gets..
3988 $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
3990 if (!is_string($message)) {
3991 $message = print_r($message,true);
3993 if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
3994 return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
3997 if (!ini_get('html_errors')) {
3998 echo "$class : $logtype : $message\n";
4002 if (!is_string($message)) {
4003 $message = print_r($message,true);
4005 $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
4006 echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
4010 * sets and returns debug level
4011 * eg. DB_DataObject::debugLevel(4);
4013 * @param int $v level
4017 function debugLevel($v = null)
4019 global $_DB_DATAOBJECT;
4020 if (empty($_DB_DATAOBJECT['CONFIG'])) {
4021 DB_DataObject::_loadConfig();
4024 $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4025 $_DB_DATAOBJECT['CONFIG']['debug'] = $v;
4028 return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4032 * Last Error that has occured
4033 * - use $this->_lastError or
4034 * $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4037 * @var object PEAR_Error (or false)
4039 var $_lastError = false;
4042 * Default error handling is to create a pear error, but never return it.
4043 * if you need to handle errors you should look at setting the PEAR_Error callback
4044 * this is due to the fact it would wreck havoc on the internal methods!
4046 * @param int $message message
4047 * @param int $type type
4048 * @param int $behaviour behaviour (die or continue!);
4050 * @return error object
4052 function raiseError($message, $type = null, $behaviour = null)
4054 global $_DB_DATAOBJECT;
4056 if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
4059 $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4061 // this will never work totally with PHP's object model.
4062 // as this is passed on static calls (like staticGet in our case)
4064 if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
4065 $this->_lastError = $error;
4068 $_DB_DATAOBJECT['LASTERROR'] = $error;
4070 // no checks for production here?....... - we log errors before we throw them.
4071 DB_DataObject::debug($message,'ERROR',1);
4074 if (PEAR::isError($message)) {
4077 require_once 'DB/DataObject/Error.php';
4078 $error = PEAR::raiseError($message, $type, $behaviour,
4079 $opts=null, $userinfo=null, 'DB_DataObject_Error'
4087 * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
4089 * After Profiling DB_DataObject, I discoved that the debug calls where taking
4090 * considerable time (well 0.1 ms), so this should stop those calls happening. as
4091 * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
4092 * THIS STILL NEEDS FURTHER INVESTIGATION
4095 * @return object an error object
4097 function _loadConfig()
4099 global $_DB_DATAOBJECT;
4101 $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
4106 * Free global arrays associated with this object.
4114 global $_DB_DATAOBJECT;
4116 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
4117 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
4119 if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4120 unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
4122 // clear the staticGet cache as well.
4123 $this->_clear_cache();
4124 // this is a huge bug in DB!
4125 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4126 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
4132 /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
4134 function _get_table() { return $this->table(); }
4135 function _get_keys() { return $this->keys(); }
4141 // technially 4.3.2RC1 was broken!!
4142 // looks like 4.3.3 may have problems too....
4143 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
4145 if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
4146 if (version_compare( phpversion(), "5") < 0) {
4147 overload('DB_DataObject');
4149 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;