/**
* Object Based Database Query Builder and data store
*
- * PHP versions 4 and 5
+ * For PHP versions 4,5 and 6
*
- * LICENSE: This source file is subject to version 3.0 of the PHP license
+ * LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt. If you did not receive a copy of
+ * http://www.php.net/license/3_01.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @package DB_DataObject
* @author Alan Knowles <alan@akbkhome.com>
* @copyright 1997-2006 The PHP Group
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version CVS: $Id: DataObject.php,v 1.439 2008/01/30 02:14:06 alan_k Exp $
+ * @license http://www.php.net/license/3_01.txt PHP License 3.01
+ * @version CVS: $Id: DataObject.php 284150 2009-07-15 23:27:59Z alan_k $
* @link http://pear.php.net/package/DB_DataObject
*/
* @access private
* @var string
*/
- var $_DB_DataObject_version = "1.8.8";
+ var $_DB_DataObject_version = "1.8.11";
/**
* The Database table (used by table extends)
if ($leftq || $useNative) {
$table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
- $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
+
+ if (($dbtype == 'pgsql') && empty($leftq)) {
+ $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
+ } else {
+ $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
+ }
+
* build the condition only using the object parameters.
*
* @access public
- * @return mixed True on success, false on failure, 0 on no data affected
+ * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
*/
function delete($useWhere = false)
{
if (($this->_query !== false) && $this->_query['condition']) {
$table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
- $sql = "DELETE FROM {$table} {$this->_query['condition']}{$extra_cond}";
+ $sql = "DELETE ";
+ // using a joined delete. - with useWhere..
+ $sql .= (!empty($this->_join) && $useWhere) ?
+ "{$table} FROM {$table} {$this->_join} " :
+ "FROM {$table} ";
+
+ $sql .= $this->_query['condition']. $extra_cond;
// add limit..
}
$keys = $this->keys();
- if (!$keys[0] && !is_string($countWhat)) {
+ if (empty($keys[0]) && (!is_string($countWhat) || (strtoupper($countWhat) == 'DISTINCT'))) {
$this->raiseError(
- "You cannot do run count without keys - use \$do->keys('id');",
+ "You cannot do run count without keys - use \$do->count('id'), or use \$do->count('distinct id')';",
DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
return false;
}
$table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
- $key_col = ($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]);
+ $key_col = empty($keys[0]) ? '' : (($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]));
$as = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
// support distinct on default keys.
// technically postgres native here...
// we need to get the new improved tabledata sorted out first.
- if ( in_array($dbtype , array('psql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
+ if ( in_array($dbtype , array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
($table[$usekey] & DB_DATAOBJECT_INT) &&
isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
) {
$this->_loadConfig();
}
// Set database driver for reference
- $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
- // is it already connected ?
-
+ $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
+ 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
+
+ // is it already connected ?
if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
+
+ // connection is an error...
if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
return $this->raiseError(
$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
}
- if (!$this->_database) {
+ if (empty($this->_database)) {
$this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
$hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
// try and work out what to use for the dsn !
$options= &$_DB_DATAOBJECT['CONFIG'];
+ // if the databse dsn dis defined in the object..
$dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
if (!$dsn) {
$this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Checking for database database_{$this->_database} in options","CONNECT");
+ $this->debug("Checking for database specific ini ('{$this->_database}') : database_{$this->_database} in options","CONNECT");
}
if ($this->_database && !empty($options["database_{$this->_database}"])) {
-
$dsn = $options["database_{$this->_database}"];
} else if (!empty($options['database'])) {
$dsn = $options['database'];
+
}
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
$this->debug("USING CACHED CONNECTION", "CONNECT",3);
}
+
+
+
if (!$this->_database) {
$hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
return true;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("NEW CONNECTION", "CONNECT",3);
+ $this->debug("NEW CONNECTION TP DATABASE :" .$this->_database , "CONNECT",3);
/* actualy make a connection */
$this->debug(print_r($dsn,true) ." {$this->_database_dsn_md5}", "CONNECT",3);
}
);
}
-
- if (!$this->_database) {
+
+ if (empty($this->_database)) {
$hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
$this->_database = ($db_driver != 'DB' && $hasGetDatabase)
$t= explode(' ',microtime());
$_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
-
- do {
- if ($_DB_driver == 'DB') {
- $result = $DB->query($string);
- } else {
- switch (strtolower(substr(trim($string),0,6))) {
+ for ($tries = 0;$tries < 3;$tries++) {
- case 'insert':
- case 'update':
- case 'delete':
- $result = $DB->exec($string);
- break;
-
- default:
- $result = $DB->query($string);
- break;
+ if ($_DB_driver == 'DB') {
+
+ $result = $DB->query($string);
+ } else {
+ switch (strtolower(substr(trim($string),0,6))) {
+
+ case 'insert':
+ case 'update':
+ case 'delete':
+ $result = $DB->exec($string);
+ break;
+
+ default:
+ $result = $DB->query($string);
+ break;
+ }
}
+
+ // see if we got a failure.. - try again a few times..
+ if (!is_a($result,'PEAR_Error')) {
+ break;
+ }
+ if ($result->getCode() != -14) { // *DB_ERROR_NODBSELECTED
+ break; // not a connection error..
+ }
+ sleep(1); // wait before retyring..
+ $DB->connect($DB->dsn);
}
-
- // try to reconnect, at most 3 times
- $again = false;
- if (is_a($result, 'PEAR_Error')
- AND $result->getCode() == DB_ERROR_NODBSELECTED
- AND $cpt++<3) {
- $DB->disconnect();
- sleep(1);
- $DB->connect($DB->dsn);
- $again = true;
- }
-
- } while ($again);
+
if (is_a($result,'PEAR_Error')) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
* use @ to silence it (if you are sure it is acceptable)
* eg. $do = @DB_DataObject::factory('person')
*
- * table name will eventually be databasename/table
+ * table name can bedatabasename/table
* - and allow modular dataobjects to be written..
* (this also helps proxy creation)
*
- *
+ * Experimental Support for Multi-Database factory eg. mydatabase.mytable
+ *
+ *
* @param string $table tablename (use blank to create a new instance of the same class.)
* @access private
* @return DataObject|PEAR_Error
function factory($table = '') {
global $_DB_DATAOBJECT;
+
+
+ // multi-database support.. - experimental.
+ $database = '';
+
+ if (strpos( $table,'/') !== false ) {
+ list($database,$table) = explode('.',$table, 2);
+
+ }
+
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
+ // no configuration available for database
+ if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_'.$database])) {
+ return DB_DataObject::raiseError(
+ "unable to find database_{$database} in Configuration, It is required for factory with database"
+ , 0, PEAR_ERROR_DIE );
+ }
+
+
if ($table === '') {
if (is_a($this,'DB_DataObject') && strlen($this->__table)) {
}
}
-
+ // does this need multi db support??
$p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
$_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
$class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
-
$ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
+
$class = $ce ? $class : DB_DataObject::_autoloadClass($class);
// proxy = full|light
if (!$class && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
+
+ DB_DataObject::debug("FAILED TO Autoload $database.$table - using proxy.","FACTORY",1);
+
+
$proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
+ // if you have loaded (some other way) - dont try and load it again..
class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
"factory could not find class $class from $table",
DB_DATAOBJECT_ERROR_INVALIDCONFIG);
}
-
- return new $class;
+ $ret = new $class;
+ if (!empty($database)) {
+ DB_DataObject::debug("Setting database to $database","FACTORY",1);
+ $ret->database($database);
+ }
+ return $ret;
}
/**
* autoload Class
return;
}
-
+ //echo '<PRE>'; print_r(func_get_args());
$useWhereAsOn = false;
// support for 2nd argument as an array of options
if (is_array($joinType)) {
$DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
+ /// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
-
+ /* otherwise see if there are any links from this table to the obj. */
+ //print_r($this->links());
+ if (($ofield === false) && ($links = $this->links())) {
+ foreach ($links as $k => $v) {
+ /* link contains {this column} = {linked table}:{linked column} */
+ $ar = explode(':', $v);
+ // Feature Request #4266 - Allow joins with multiple keys
+ if (strpos($k, ',') !== false) {
+ $k = explode(',', $k);
+ }
+ if (strpos($ar[1], ',') !== false) {
+ $ar[1] = explode(',', $ar[1]);
+ }
+
+ if ($ar[0] == $obj->__table) {
+ if ($joinCol !== false) {
+ if ($k == $joinCol) {
+ $tfield = $k;
+ $ofield = $ar[1];
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ $tfield = $k;
+ $ofield = $ar[1];
+ break;
+ }
+ }
+ }
+ }
/* look up the links for obj table */
//print_r($obj->links());
if (!$ofield && ($olinks = $obj->links())) {
}
}
- /* otherwise see if there are any links from this table to the obj. */
- //print_r($this->links());
- if (($ofield === false) && ($links = $this->links())) {
- foreach ($links as $k => $v) {
- /* link contains {this column} = {linked table}:{linked column} */
- $ar = explode(':', $v);
- // Feature Request #4266 - Allow joins with multiple keys
- if (strpos($k, ',') !== false) {
- $k = explode(',', $k);
- }
- if (strpos($ar[1], ',') !== false) {
- $ar[1] = explode(',', $ar[1]);
- }
-
- if ($ar[0] == $obj->__table) {
- if ($joinCol !== false) {
- if ($k == $joinCol) {
- $tfield = $k;
- $ofield = $ar[1];
- break;
- } else {
- continue;
- }
- } else {
- $tfield = $k;
- $ofield = $ar[1];
- break;
- }
- }
- }
- }
// finally if these two table have column names that match do a join by default on them
if (($ofield === false) && $joinCol) {
case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
// Feature Request #4266 - Allow joins with multiple keys
- $this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
+ $jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
+ //$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
if (is_array($ofield)) {
$key_count = count($ofield);
for($i = 0; $i < $key_count; $i++) {
if ($i == 0) {
- $this->_join .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
+ $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
}
else {
- $this->_join .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
+ $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
}
}
- $this->_join .= ' ' . $appendJoin . ' ';
+ $jadd .= ' ' . $appendJoin . ' ';
} else {
- $this->_join .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
+ $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
}
-
+ // jadd avaliable for debugging join build.
+ //echo $jadd ."\n";
+ $this->_join .= $jadd;
break;
case '': // this is just a standard multitable select..
continue;
}
- if (empty($from[$k]) && $skipEmpty) {
+ if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
continue;
}
*
* PHP versions 4 and 5
*
- * LICENSE: This source file is subject to version 3.0 of the PHP license
+ * LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt. If you did not receive a copy of
+ * http://www.php.net/license/3_01.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @package DB_DataObject
* @author Alan Knowles <alan@akbkhome.com>
* @copyright 1997-2006 The PHP Group
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version CVS: $Id: Generator.php,v 1.141 2008/01/30 02:29:39 alan_k Exp $
+ * @license http://www.php.net/license/3_01.txt PHP License 3.01
+ * @version CVS: $Id: Generator.php 284150 2009-07-15 23:27:59Z alan_k $
* @link http://pear.php.net/package/DB_DataObject
*/
/**
* set portability and some modules to fetch the informations
*/
- $__DB->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE);
+ $db_options = PEAR::getStaticProperty('MDB2','options');
+ if (empty($db_options)) {
+ $__DB->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE);
+ }
+
$__DB->loadModule('Manager');
$__DB->loadModule('Reverse');
}
} else {
$defs = $__DB->reverse->tableInfo($quotedTable);
// rename the length value, so it matches db's return.
- foreach ($defs as $k => $v) {
- if (!isset($defs[$k]['length'])) {
- continue;
- }
- $defs[$k]['len'] = $defs[$k]['length'];
- }
+
}
if (is_a($defs,'PEAR_Error')) {
if (!is_array($def)) {
continue;
}
-
+ // rename the length value, so it matches db's return.
+ if (isset($def['length']) && !isset($def['len'])) {
+ $def['len'] = $def['length'];
+ }
$this->_definitions[$table][] = (object) $def;
}
$fk = array();
foreach($this->tables as $this->table) {
- $res =& $DB->query('SHOW CREATE TABLE ' . $this->table);
+ $quotedTable = !empty($options['quote_identifiers_tableinfo']) ? $DB->quoteIdentifier($table) : $this->table;
+
+ $res =& $DB->query('SHOW CREATE TABLE ' . $quotedTable );
+
if (PEAR::isError($res)) {
die($res->getMessage());
}
function _generateDefinitionsTable()
{
global $_DB_DATAOBJECT;
-
+ $options = PEAR::getStaticProperty('DB_DataObject','options');
$defs = $this->_definitions[$this->table];
$this->_newConfig .= "\n[{$this->table}]\n";
$keys_out = "\n[{$this->table}__keys]\n";
case 'ENUM':
case 'SET': // not really but oh well
+
+ case 'POINT': // mysql geometry stuff - not really string - but will do..
+
case 'TIMESTAMPTZ': // postgres
case 'BPCHAR': // postgres
case 'INTERVAL': // postgres (eg. '12 days')
DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME;
break;
-
- case 'TINYBLOB':
+
case 'BLOB': /// these should really be ignored!!!???
+ case 'TINYBLOB':
case 'MEDIUMBLOB':
case 'LONGBLOB':
+
+ case 'CLOB': // oracle character lob support
+
case 'BYTEA': // postgres blob support..
$type = DB_DATAOBJECT_STR + DB_DATAOBJECT_BLOB;
break;
+
default:
echo "*****************************************************************\n".
"** WARNING UNKNOWN TYPE **\n".
// only use primary key or nextval(), cause the setFrom blocks you setting all key items...
// if no keys exist fall back to using unique
//echo "\n{$t->name} => {$t->flags}\n";
- if (preg_match("/(auto_increment|nextval\()/i",rawurldecode($t->flags))
+ $secondary_key_match = isset($options['generator_secondary_key_match']) ? $options['generator_secondary_key_match'] : 'primary|unique';
+
+ if (preg_match('/(auto_increment|nextval\()/i',rawurldecode($t->flags))
|| (isset($t->autoincrement) && ($t->autoincrement === true))) {
// native sequences = 2
}
$ret_keys_primary[$t->name] = 'N';
- } else if (preg_match("/(primary|unique)/i",$t->flags)) {
+ } else if ($secondary_key_match && preg_match('/('.$secondary_key_match.')/i',$t->flags)) {
// keys.. = 1
$key_type = 'K';
if (!preg_match("/(primary)/i",$t->flags)) {
// then we should add var $_database = here
// as database names may not always match..
+ if (empty($GLOBALS['_DB_DATAOBJECT']['CONFIG'])) {
+ DB_DataObject::_loadConfig();
+ }
+
+ // Only include the $_database property if the omit_database_var is unset or false
-
-
- if (isset($options["database_{$this->_database}"])) {
+ if (isset($options["database_{$this->_database}"]) && empty($GLOBALS['_DB_DATAOBJECT']['CONFIG']['generator_omit_database_var'])) {
$body .= " {$var} \$_database = '{$this->_database}'; {$p}// database name (used with database_{*} config)\n";
}
$padding = (30 - strlen($t->name));
if ($padding < 2) $padding =2;
$p = str_repeat(' ',$padding) ;
-
- $body .=" {$var} \${$t->name}; {$p}// {$t->type}({$t->len}) {$t->flags}\n";
-
+
+ $length = empty($t->len) ? '' : '('.$t->len.')';
+ $body .=" {$var} \${$t->name}; {$p}// {$t->type}$length {$t->flags}\n";
+
// can not do set as PEAR::DB table info doesnt support it.
//if (substr($t->Type,0,3) == "set")
// $sets[$t->Field] = "array".substr($t->Type,3);
$__DB->loadModule('Manager');
$__DB->loadModule('Reverse');
}
- $quotedTable = !empty($options['quote_identifiers']) ?
+ $quotedTable = !empty($options['quote_identifiers_tableinfo']) ?
$__DB->quoteIdentifier($table) : $table;
if (!$is_MDB2) {