*/
-/* ===========================================================================
+/* ===========================================================================
*
* !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
*
- * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
- * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
+ * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
+ * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
* this file. reducing the optimization level may also solve the segfault.
* ===========================================================================
*/
* We are duping fetchmode constants to be compatible with
* both DB and MDB2
*/
-define('DB_DATAOBJECT_FETCHMODE_ORDERED',1);
-define('DB_DATAOBJECT_FETCHMODE_ASSOC',2);
+define('DB_DATAOBJECT_FETCHMODE_ORDERED', 1);
+define('DB_DATAOBJECT_FETCHMODE_ASSOC', 2);
* these are constants for the get_table array
* user to determine what type of escaping is required around the object vars.
*/
-define('DB_DATAOBJECT_INT', 1); // does not require ''
-define('DB_DATAOBJECT_STR', 2); // requires ''
+define('DB_DATAOBJECT_INT', 1); // does not require ''
+define('DB_DATAOBJECT_STR', 2); // requires ''
define('DB_DATAOBJECT_DATE', 4); // is date #TODO
define('DB_DATAOBJECT_TIME', 8); // is time #TODO
define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
-define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
+define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
define('DB_DATAOBJECT_BLOB', 64); // is blob type
-define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
-define('DB_DATAOBJECT_MYSQLTIMESTAMP' , 256); // mysql timestamps (ignored by update/insert)
+define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
+define('DB_DATAOBJECT_MYSQLTIMESTAMP', 256); // mysql timestamps (ignored by update/insert)
/*
* Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
*/
-//define('DB_DATAOBJECT_NO_OVERLOAD',true)
+//define('DB_DATAOBJECT_NO_OVERLOAD',true)
/**
* the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
*/
-define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
-define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
+define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
+define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
-define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
-define('DB_DATAOBJECT_ERROR_INVALID_CALL' ,-7); // overlad getter/setter failure
+define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
+define('DB_DATAOBJECT_ERROR_INVALID_CALL', -7); // overlad getter/setter failure
/**
* Used in methods like delete() and count() to specify that the method should
if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
-
- class DB_DataObject_Overload
+ class DB_DataObject_Overload
{
- function __call($method,$args)
+ public function __call($method, $args)
{
$return = null;
- $this->_call($method,$args,$return);
+ $this->_call($method, $args, $return);
return $return;
}
- function __sleep()
+ public function __sleep()
{
- return array_keys(get_object_vars($this)) ;
+ return array_keys(get_object_vars($this)) ;
}
}
} else {
- class DB_DataObject_Overload {}
+ class DB_DataObject_Overload
+ {
+ }
}
class DB_DataObject extends DB_DataObject_Overload
{
- /**
- * The Version - use this to check feature changes
- *
- * @access private
- * @var string
- */
- var $_DB_DataObject_version = "1.11.3";
+ /**
+ * The Version - use this to check feature changes
+ *
+ * @access private
+ * @var string
+ */
+ public $_DB_DataObject_version = "1.11.3";
/**
* The Database table (used by table extends)
* @access private
* @var string
*/
- var $__table = ''; // database table
+ public $__table = ''; // database table
/**
* The Number of rows returned from a query
* @access public
* @var int
*/
- var $N = 0; // Number of rows returned from a query
+ public $N = 0; // Number of rows returned from a query
/* ============================================================= */
/* Major Public Methods */
* @access public
* @return int No. of rows
*/
- function get($k = null, $v = null)
+ public function get($k = null, $v = null)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
$k = $keys[0];
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$k $v " .print_r($keys,true), "GET");
+ $this->debug("$k $v " .print_r($keys, true), "GET");
}
if ($v === null) {
*
* $id = $do->pid();
*
- * @return the id
+ * @return the id
*/
- function pid()
+ public function pid()
{
$keys = $this->keys();
if (!$keys) {
- $this->raiseError("No Keys available for {$this->tableName()}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ $this->raiseError(
+ "No Keys available for {$this->tableName()}",
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
$k = $keys[0];
- if (empty($this->$k)) { // we do not
- $this->raiseError("pid() called on Object where primary key value not available",
- DB_DATAOBJECT_ERROR_NODATA);
+ if (empty($this->$k)) { // we do not
+ $this->raiseError(
+ "pid() called on Object where primary key value not available",
+ DB_DATAOBJECT_ERROR_NODATA
+ );
return false;
}
return $this->$k;
/**
* build the basic select query.
- *
+ *
* @access private
*/
- function _build_select()
+ public function _build_select()
{
global $_DB_DATAOBJECT;
$quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
$DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
}
$tn = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName()) ;
- if (!empty($this->_query['derive_table']) && !empty($this->_query['derive_select']) ) {
+ if (!empty($this->_query['derive_table']) && !empty($this->_query['derive_select'])) {
// this is a derived select..
// not much support in the api yet..
- $sql = 'SELECT ' .
+ $sql = 'SELECT ' .
$this->_query['derive_select']
.' FROM ( SELECT'.
$this->_query['data_select'] . " \n" .
') ' . $this->_query['derive_table'];
return $sql;
-
-
}
* will return $object->N
*
* if an error occurs $object->N will be set to false and return value will also be false;
- * if numRows is not supported it will
- *
+ * if numRows is not supported it will
+ *
*
* @param boolean $n Fetch first result
* @access public
* @return mixed (number of rows returned, or true if numRows fetching is not supported)
*/
- function find($n = false)
+ public function find($n = false)
{
global $_DB_DATAOBJECT;
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($n, "find",1);
+ $this->debug($n, "find", 1);
}
if (!strlen($this->tableName())) {
// xdebug can backtrace this!
- trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
+ trigger_error("NO \$__table SPECIFIED in class definition", E_USER_ERROR);
}
$this->N = 0;
$query_before = $this->_query;
$sql = $this->_build_select();
- foreach ($this->_query['unions'] as $union_ar) {
+ foreach ($this->_query['unions'] as $union_ar) {
$sql .= $union_ar[1] . $union_ar[0]->_build_select() . " \n";
}
/* We are checking for method modifyLimitQuery as it is PEAR DB specific */
- if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
+ if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
/* PEAR DB specific */
if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
- $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
+ $sql = $DB->modifyLimitQuery($sql, $this->_query['limit_start'], $this->_query['limit_count']);
}
} else {
/* theoretically MDB2! */
if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
- $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
- }
+ $DB->setLimit($this->_query['limit_count'], $this->_query['limit_start']);
+ }
}
$err = $this->_query($sql);
- if (is_a($err,'PEAR_Error')) {
+ if (is_a($err, 'PEAR_Error')) {
return false;
}
// find(true)
$ret = $this->N;
- if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
+ if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
// clear up memory if nothing found!?
unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
}
- if ($n && $this->N > 0 ) {
+ if ($n && $this->N > 0) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
$this->debug("ABOUT TO AUTOFETCH", "find", 1);
}
* @access public
* @return boolean on success
*/
- function fetch()
+ public function fetch()
{
-
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
if (empty($this->N)) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
+ $this->debug("No data returned from FIND (eg. N is 0)", "FETCH", 3);
}
return false;
}
- if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
- !is_object($result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
- {
+ if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
+ !is_object($result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
$this->debug('fetched on object after fetch completed (no results found)');
}
$array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($array),"FETCH");
+ $this->debug(serialize($array), "FETCH");
}
// fetched after last row..
if ($array === null) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $t= explode(' ',microtime());
+ $t= explode(' ', microtime());
- $this->debug("Last Data Fetch'ed after " .
- ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
+ $this->debug(
+ "Last Data Fetch'ed after " .
+ ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME']) .
" seconds",
- "FETCH", 1);
+ "FETCH",
+ 1
+ );
}
// reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
$_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
}
$replace = array('.', ' ');
- foreach($array as $k=>$v) {
+ foreach ($array as $k=>$v) {
// use strpos as str_replace is slow.
$kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
$k : str_replace($replace, '_', $k);
// set link flag
$this->_link_loaded=false;
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->tableName()} DONE", "fetchrow",2);
+ $this->debug("{$this->tableName()} DONE", "fetchrow", 2);
}
if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
$this->_query = false;
}
- /**
- * fetches all results as an array,
- *
- * return format is dependant on args.
- * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
- *
- * A) Array of values (eg. a list of 'id')
- *
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1')
- * $ar = $x->fetchAll('id');
- * -- returns array(1,2,3,4,5)
- *
- * B) Array of values (not from table)
- *
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1');
- * $x->selectAdd();
- * $x->selectAdd('distinct(group_id) as group_id');
- * $ar = $x->fetchAll('group_id');
- * -- returns array(1,2,3,4,5)
- * *
- * C) A key=>value associative array
- *
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1')
- * $ar = $x->fetchAll('id','name');
- * -- returns array(1=>'fred',2=>'blogs',3=> .......
- *
- * D) array of objects
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1');
- * $ar = $x->fetchAll();
- *
- * E) array of arrays (for example)
- * $x = DB_DataObject::factory('mytable');
- * $x->whereAdd('something = 1');
- * $ar = $x->fetchAll(false,false,'toArray');
- *
- *
- * @param string|false $k key
- * @param string|false $v value
- * @param string|false $method method to call on each result to get array value (eg. 'toArray')
- * @access public
- * @return array format dependant on arguments, may be empty
- */
- function fetchAll($k= false, $v = false, $method = false)
+ /**
+ * fetches all results as an array,
+ *
+ * return format is dependant on args.
+ * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
+ *
+ * A) Array of values (eg. a list of 'id')
+ *
+ * $x = DB_DataObject::factory('mytable');
+ * $x->whereAdd('something = 1')
+ * $ar = $x->fetchAll('id');
+ * -- returns array(1,2,3,4,5)
+ *
+ * B) Array of values (not from table)
+ *
+ * $x = DB_DataObject::factory('mytable');
+ * $x->whereAdd('something = 1');
+ * $x->selectAdd();
+ * $x->selectAdd('distinct(group_id) as group_id');
+ * $ar = $x->fetchAll('group_id');
+ * -- returns array(1,2,3,4,5)
+ * *
+ * C) A key=>value associative array
+ *
+ * $x = DB_DataObject::factory('mytable');
+ * $x->whereAdd('something = 1')
+ * $ar = $x->fetchAll('id','name');
+ * -- returns array(1=>'fred',2=>'blogs',3=> .......
+ *
+ * D) array of objects
+ * $x = DB_DataObject::factory('mytable');
+ * $x->whereAdd('something = 1');
+ * $ar = $x->fetchAll();
+ *
+ * E) array of arrays (for example)
+ * $x = DB_DataObject::factory('mytable');
+ * $x->whereAdd('something = 1');
+ * $ar = $x->fetchAll(false,false,'toArray');
+ *
+ *
+ * @param string|false $k key
+ * @param string|false $v value
+ * @param string|false $method method to call on each result to get array value (eg. 'toArray')
+ * @access public
+ * @return array format dependant on arguments, may be empty
+ */
+ public function fetchAll($k= false, $v = false, $method = false)
{
// should it even do this!!!?!?
- if ($k !== false &&
+ if ($k !== false &&
( // only do this is we have not been explicit..
- empty($this->_query['data_select']) ||
+ empty($this->_query['data_select']) ||
($this->_query['data_select'] == '*')
)
) {
$ret[$this->$k] = $this->$v;
continue;
}
- $ret[] = $k === false ?
+ $ret[] = $k === false ?
($method == false ? clone($this) : $this->$method())
: $this->$k;
}
return $ret;
-
}
* @access public
* @return string|PEAR::Error - previous condition or Error when invalid args found
*/
- function whereAdd($cond = false, $logic = 'AND')
+ public function whereAdd($cond = false, $logic = 'AND')
{
// for PHP5.2.3 - there is a bug with setting array properties of an object.
$_query = $this->_query;
if (!isset($this->_query) || ($_query === false)) {
return $this->raiseError(
- "You cannot do two queries on the same object (clone it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (clone it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
}
if ($cond === false) {
$r = $this->_query['condition'];
$_query['condition'] = '';
$this->_query = $_query;
- return preg_replace('/^\s+WHERE\s+/','',$r);
+ return preg_replace('/^\s+WHERE\s+/', '', $r);
}
// check input...= 0 or ' ' == error!
if (!trim($cond)) {
*
* @param string $key key column to match
* @param array $list list of values to match
- * @param string $type string|int|integer|float|bool cast to type.
+ * @param string $type string|int|integer|float|bool cast to type.
* @param string $logic optional logic to call whereAdd with eg. "OR" (defaults to "AND")
* @access public
* @return string|PEAR::Error - previous condition or Error when invalid args found
*/
- function whereAddIn($key, $list, $type, $logic = 'AND')
+ public function whereAddIn($key, $list, $type, $logic = 'AND')
{
$not = '';
if ($key[0] == '!') {
$not = 'NOT ';
$key = substr($key, 1);
}
- // fix type for short entry.
- $type = $type == 'int' ? 'integer' : $type;
+ // fix type for short entry.
+ $type = $type == 'int' ? 'integer' : $type;
if ($type == 'string') {
$this->_connect();
}
$ar = array();
- foreach($list as $k) {
+ foreach ($list as $k) {
settype($k, $type);
$ar[] = $type == 'string' ? $this->_quote($k) : $k;
}
if (!$ar) {
return $not ? $this->_query['condition'] : $this->whereAdd("1=0");
}
- return $this->whereAdd("$key $not IN (". implode(',', $ar). ')', $logic );
+ return $this->whereAdd("$key $not IN (". implode(',', $ar). ')', $logic);
}
* @access public
* @return none|PEAR::Error - invalid args only
*/
- function orderBy($order = false)
+ public function orderBy($order = false)
{
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($order === false) {
* @access public
* @return none|PEAR::Error - invalid args only
*/
- function groupBy($group = false)
+ public function groupBy($group = false)
{
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($group === false) {
* @access public
* @return none|PEAR::Error - invalid args only
*/
- function having($having = false)
+ public function having($having = false)
{
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($having === false) {
/**
* Adds a using Index
*
- * $object->useIndex(); //reset the use Index
+ * $object->useIndex(); //reset the use Index
* $object->useIndex("some_index");
*
* Note do not put unfiltered user input into theis method.
* This is mysql specific at present? - might need altering to support other databases.
- *
+ *
* @param string|array $index index or indexes to use.
* @access public
* @return none|PEAR::Error - invalid args only
*/
- function useIndex($index = false)
+ public function useIndex($index = false)
{
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($index=== false) {
return;
}
// check input...= 0 or ' ' == error!
- if ((is_string($index) && !trim($index)) || (is_array($index) && !count($index)) ) {
+ if ((is_string($index) && !trim($index)) || (is_array($index) && !count($index))) {
return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
}
$index = is_array($index) ? implode(', ', $index) : $index;
$this->_query['useindex'] = " USE INDEX ({$index}) ";
return;
}
- $this->_query['useindex'] = substr($this->_query['useindex'],0, -2) . ", {$index}) ";
+ $this->_query['useindex'] = substr($this->_query['useindex'], 0, -2) . ", {$index}) ";
}
/**
* Sets the Limit
* @access public
* @return none|PEAR::Error - invalid args only
*/
- function limit($a = null, $b = null)
+ public function limit($a = null, $b = null)
{
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($a === null) {
- $this->_query['limit_start'] = '';
- $this->_query['limit_count'] = '';
- return;
+ $this->_query['limit_start'] = '';
+ $this->_query['limit_count'] = '';
+ return;
}
// check input...= 0 or ' ' == error!
- if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
+ if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
|| (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
}
$this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
$this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
-
}
/**
* @access public
* @return mixed null or old string if you reset it.
*/
- function selectAdd($k = null)
+ public function selectAdd($k = null)
{
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($k === null) {
* @access public
* @return void
*/
- function selectAs($from = null,$format = '%s',$tableName=false)
+ public function selectAs($from = null, $format = '%s', $tableName=false)
{
global $_DB_DATAOBJECT;
if ($this->_query === false) {
$this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do two queries on the same object (copy it before finding)",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
if ($from === null) {
- // blank the '*'
+ // blank the '*'
$this->selectAdd();
$from = $this;
}
$this->_connect();
$DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
$s = $DB->quoteIdentifier($s);
- $format = $DB->quoteIdentifier($format);
+ $format = $DB->quoteIdentifier($format);
}
foreach ($from as $k) {
- $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
+ $this->selectAdd(sprintf("{$s}.{$s} as {$format}", $table, $k, $k));
}
$this->_query['data_select'] .= "\n";
}
* @access public
* @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
*/
- function insert()
+ public function insert()
{
global $_DB_DATAOBJECT;
$items = $this->table();
if (!$items) {
- $this->raiseError("insert:No table definition for {$this->tableName()}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ $this->raiseError(
+ "insert:No table definition for {$this->tableName()}",
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
$options = $_DB_DATAOBJECT['CONFIG'];
$rightq = '';
$seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]) ?
- $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] :
+ $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] :
$this->sequenceKey();
$key = isset($seqKeys[0]) ? $seqKeys[0] : false;
$dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
- // nativeSequences or Sequences..
+ // nativeSequences or Sequences..
// big check for using sequences
- if (($key !== false) && !$useNative) {
-
+ if (($key !== false) && !$useNative) {
if (!$seq) {
$keyvalue = $DB->nextId($this->tableName());
} else {
$f = $DB->getOption('seqname_format');
- $DB->setOption('seqname_format','%s');
+ $DB->setOption('seqname_format', '%s');
$keyvalue = $DB->nextId($seq);
- $DB->setOption('seqname_format',$f);
+ $DB->setOption('seqname_format', $f);
}
if (PEAR::isError($keyvalue)) {
$this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
|| strtolower($options['disable_null_strings']) !== 'full' ;
- foreach($items as $k => $v) {
+ foreach ($items as $k => $v) {
// if we are using autoincrement - skip the column...
if ($key && ($k == $key) && $useNative) {
// Ignore INTEGERS which aren't set to a value - or empty string..
- if ( (!isset($this->$k) || ($v == 1 && $this->$k === ''))
+ if ((!isset($this->$k) || ($v == 1 && $this->$k === ''))
&& $ignore_null
) {
continue;
}
- // dont insert data into mysql timestamps
+ // dont insert data into mysql timestamps
// use query() if you really want to do this!!!!
if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
continue;
$leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
- if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
- $value = $this->$k->toString($v,$DB);
+ if (is_object($this->$k) && is_a($this->$k, 'DB_DataObject_Cast')) {
+ $value = $this->$k->toString($v, $DB);
if (PEAR::isError($value)) {
- $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
+ $this->raiseError($value->toString(), DB_DATAOBJECT_ERROR_INVALIDARGS);
return false;
}
$rightq .= $value;
}
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
+ if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this, $k)) {
$rightq .= " NULL ";
continue;
}
- // DATE is empty... on a col. that can be null..
+ // DATE is empty... on a col. that can be null..
// note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
+ if (!$this->$k &&
+ (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
!($v & DB_DATAOBJECT_NOTNULL)) {
-
$rightq .= " NULL ";
continue;
}
if ($v & DB_DATAOBJECT_STR) {
$rightq .= $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
+ ($v & DB_DATAOBJECT_BOOL) ?
+ // this is thanks to the braindead idea of postgres to
// use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
+ (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
$this->$k
)) . " ";
continue;
}
/* flag up string values - only at debug level... !!!??? */
if (is_object($this->$k) || is_array($this->$k)) {
- $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k,true),'ERROR');
+ $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k, true), 'ERROR');
}
// at present we only cast to integers
// - V2 may store additional data about float/int
$rightq .= ' ' . intval($this->$k) . ' ';
-
}
// not sure why we let empty insert here.. - I guess to generate a blank row..
if (($dbtype == 'pgsql') && empty($leftq)) {
$r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
} else {
- $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
+ $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
}
break;
case 'mssql':
- // note this is not really thread safe - you should wrapp it with
+ // note this is not really thread safe - you should wrapp it with
// transactions = eg.
// $db->query('BEGIN');
// $db->insert();
return false;
}
$this->$key = $mssql_key;
- break;
+ break;
case 'pgsql':
if (!$seq) {
}
$db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
$method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
- $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
+ $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
if (PEAR::isError($pgsql_key)) {
break;
case 'ifx':
- $this->$key = array_shift (
- ifx_fetch_row (
+ $this->$key = array_shift(
+ ifx_fetch_row(
ifx_query(
"select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
IFX_SCROLL
- ),
+ ),
"FIRST"
)
- );
+ );
break;
}
-
}
if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
* @access public
* @return int rows affected or false on failure
*/
- function update($dataObject = false)
+ public function update($dataObject = false)
{
global $_DB_DATAOBJECT;
// connect will load the config!
the key set, and argument to update is not
DB_DATAOBJECT_WHEREADD_ONLY
". print_r(array('seq' => $seq , 'keys'=>$keys), true), DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
+ return false;
}
} else {
$keys = $this->keys();
|| strtolower($options['disable_null_strings']) !== 'full' ;
- foreach($items as $k => $v) {
+ foreach ($items as $k => $v) {
// I think this is ignoring empty vlalues
if ((!isset($this->$k) || ($v == 1 && $this->$k === ''))
&& $ignore_null
) {
- continue;
+ continue;
}
- // ignore stuff thats
+ // ignore stuff thats
// dont write things that havent changed..
if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
}
// - dont write keys to left.!!!
- if (in_array($k,$keys)) {
+ if (in_array($k, $keys)) {
continue;
}
- // dont insert data into mysql timestamps
+ // dont insert data into mysql timestamps
// use query() if you really want to do this!!!!
if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
continue;
}
- if ($settings) {
+ if ($settings) {
$settings .= ', ';
}
$kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
- if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
- $value = $this->$k->toString($v,$DB);
+ if (is_object($this->$k) && is_a($this->$k, 'DB_DataObject_Cast')) {
+ $value = $this->$k->toString($v, $DB);
if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
+ $this->raiseError($value->getMessage(), DB_DATAOBJECT_ERROR_INVALIDARG);
return false;
}
$settings .= "$kSql = $value ";
}
// special values ... at least null is handled...
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
+ if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this, $k)) {
$settings .= "$kSql = NULL ";
continue;
}
- // DATE is empty... on a col. that can be null..
+ // DATE is empty... on a col. that can be null..
// note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
+ if (!$this->$k &&
+ (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
!($v & DB_DATAOBJECT_NOTNULL)) {
-
$settings .= "$kSql = NULL ";
continue;
}
if ($v & DB_DATAOBJECT_STR) {
$settings .= "$kSql = ". $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
+ ($v & DB_DATAOBJECT_BOOL) ?
+ // this is thanks to the braindead idea of postgres to
// use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
+ (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
$this->$k
)) . ' ';
continue;
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("got keys as ".serialize($keys),3);
+ $this->debug("got keys as ".serialize($keys), 3);
}
if ($dataObject !== true) {
- $this->_build_condition($items,$keys);
+ $this->_build_condition($items, $keys);
} else {
// prevent wiping out of data!
if (empty($this->_query['condition'])) {
- $this->raiseError("update: global table update not available
+ $this->raiseError("update: global table update not available
do \$do->whereAdd('1=1'); if you really want to do that.
", DB_DATAOBJECT_ERROR_INVALIDARGS);
return false;
// echo " $settings, $this->condition ";
if ($settings && isset($this->_query) && $this->_query['condition']) {
-
$table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
$r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
}
$this->raiseError(
- "update: No Data specifed for query $settings , {$this->_query['condition']}",
- DB_DATAOBJECT_ERROR_NODATA);
+ "update: No Data specifed for query $settings , {$this->_query['condition']}",
+ DB_DATAOBJECT_ERROR_NODATA
+ );
return false;
}
* @access public
* @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
*/
- function delete($useWhere = false)
+ public function delete($useWhere = false)
{
global $_DB_DATAOBJECT;
// connect will load the config!
$DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
$quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
+ $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
if (!$useWhere) {
-
$keys = $this->keys();
$this->_query = array(); // as it's probably unset!
$this->_query['condition'] = ''; // default behaviour not to use where condition
- $this->_build_condition($this->table(),$keys);
+ $this->_build_condition($this->table(), $keys);
// if primary keys are not set then use data from rest of object.
if (!$this->_query['condition']) {
- $this->_build_condition($this->table(),array(),$keys);
+ $this->_build_condition($this->table(), array(), $keys);
}
$extra_cond = '';
- }
+ }
// don't delete without a condition
if (($this->_query !== false) && $this->_query['condition']) {
-
$table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
$sql = "DELETE ";
// using a joined delete. - with useWhere..
- $sql .= (!empty($this->_join) && $useWhere) ?
- "{$table} FROM {$table} {$this->_join} " :
+ $sql .= (!empty($this->_join) && $useWhere) ?
+ "{$table} FROM {$table} {$this->_join} " :
"FROM {$table} ";
$sql .= $this->_query['condition']. $extra_cond;
// add limit..
if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
-
- if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
+ if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
- // pear DB
- $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
-
+ // pear DB
+ $sql = $DB->modifyLimitQuery($sql, $this->_query['limit_start'], $this->_query['limit_count']);
} else {
// MDB2
- $DB->setLimit( $this->_query['limit_count'],$this->_query['limit_start']);
+ $DB->setLimit($this->_query['limit_count'], $this->_query['limit_start']);
}
-
}
* @access public
* @return boolean true on success
*/
- function fetchRow($row = null)
+ public function fetchRow($row = null)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
$this->_loadConfig();
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow",3);
+ $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow", 3);
}
if (!$this->tableName()) {
$this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
return false;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow",3);
+ $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow", 3);
}
$result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
- $array = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC,$row);
+ $array = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC, $row);
if (!is_array($array)) {
$this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
return false;
}
$replace = array('.', ' ');
- foreach($array as $k => $v) {
+ foreach ($array as $k => $v) {
// use strpos as str_replace is slow.
$kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
$k : str_replace($replace, '_', $k);
* (true|false => see below not on whereAddonly)
* (string)
* "DISTINCT" => does a distinct count on the tables 'key' column
- * otherwise => normally it counts primary keys - you can use
+ * otherwise => normally it counts primary keys - you can use
* this to do things like $do->count('distinct mycol');
- *
+ *
* @param bool $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
* we will build the condition only using the whereAdd's. Default is to
* build the condition using the object parameters as well.
- *
+ *
* @access public
* @return int
*/
- function count($countWhat = false,$whereAddOnly = false)
+ public function count($countWhat = false, $whereAddOnly = false)
{
global $_DB_DATAOBJECT;
if (!isset($t->_query)) {
$this->raiseError(
- "You cannot do run count after you have run fetch()",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ "You cannot do run count after you have run fetch()",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
$this->_connect();
$DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- if (!$whereAddOnly && $items) {
+ if (!$whereAddOnly && $items) {
$t->_build_condition($items);
}
$keys = $this->keys();
if (empty($keys[0]) && (!is_string($countWhat) || (strtoupper($countWhat) == 'DISTINCT'))) {
$this->raiseError(
- "You cannot do run count without keys - use \$do->count('id'), or use \$do->count('distinct id')';",
- DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
+ "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->tableName()) : $this->tableName());
$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.
- $countWhat = (strtoupper($countWhat) == 'DISTINCT') ?
+ $countWhat = (strtoupper($countWhat) == 'DISTINCT') ?
"DISTINCT {$table}.{$key_col}" : $countWhat;
$countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
$r = $t->_query(
"SELECT count({$countWhat}) as $as
- FROM $table {$t->_join} {$t->_query['condition']}");
+ FROM $table {$t->_join} {$t->_query['condition']}"
+ );
if (PEAR::isError($r)) {
return false;
}
// free the results - essential on oracle.
$t->free();
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug('Count returned '. $l[0] ,1);
+ $this->debug('Count returned '. $l[0], 1);
}
return (int) $l[0];
}
* @access public
* @return void or DB_Error
*/
- function query($string)
+ public function query($string)
{
return $this->_query($string);
}
* eg.
* $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
*
- * @param string $string value to be escaped
+ * @param string $string value to be escaped
* @param bool $likeEscape escapes % and _ as well. - so like queries can be protected.
* @access public
* @return string
*/
- function escape($string, $likeEscape=false)
+ public function escape($string, $likeEscape=false)
{
global $_DB_DATAOBJECT;
$this->_connect();
$ret = str_replace(array('_','%'), array('\_','\%'), $ret);
}
return $ret;
-
}
/* ==================================================== */
* @access private
* @var string
*/
- var $_database_dsn = '';
+ public $_database_dsn = '';
/**
* The Database connection id (md5 sum of databasedsn)
* @access private
* @var string
*/
- var $_database_dsn_md5 = '';
+ public $_database_dsn_md5 = '';
/**
* The Database name
* @access private
* @var string
*/
- var $_database = '';
+ public $_database = '';
/**
* The QUERY rules
- * This replaces alot of the private variables
+ * This replaces alot of the private variables
* used to build a query, it is unset after find() is run.
- *
+ *
*
*
* @access private
* @var array
*/
- var $_query = array(
+ public $_query = array(
'condition' => '', // the WHERE condition
'group_by' => '', // the GROUP BY condition
'order_by' => '', // the ORDER BY condition
* @access private
* @var integer
*/
- var $_DB_resultid;
+ public $_DB_resultid;
- /**
- * ResultFields - on the last call to fetch(), resultfields is sent here,
- * so we can clean up the memory.
- *
- * @access public
- * @var array
- */
- var $_resultFields = false;
+ /**
+ * ResultFields - on the last call to fetch(), resultfields is sent here,
+ * so we can clean up the memory.
+ *
+ * @access public
+ * @var array
+ */
+ public $_resultFields = false;
/* ============================================================== */
*
* usage :
* DB_DataObject::databaseStructure( 'databasename',
- * parse_ini_file('mydb.ini',true),
- * parse_ini_file('mydb.link.ini',true));
+ * parse_ini_file('mydb.ini',true),
+ * parse_ini_file('mydb.link.ini',true));
*
* obviously you dont have to use ini files.. (just return array similar to ini files..)
- *
- * It should append to the table structure array
*
- *
+ * It should append to the table structure array
+ *
+ *
* @param optional string name of database to assign / read
* @param optional array structure of database, and keys
* @param optional array table links
* @return true or PEAR:error on wrong paramenters.. or false if no file exists..
* or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
*/
- function databaseStructure()
+ public function databaseStructure()
{
-
global $_DB_DATAOBJECT;
- // Assignment code
+ // Assignment code
if ($args = func_get_args()) {
-
if (count($args) == 1) {
// this returns all the tables and their structure..
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Loading Generator as databaseStructure called with args",1);
+ $this->debug("Loading Generator as databaseStructure called with args", 1);
}
$x = new DB_DataObject;
$DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
$tables = $DB->getListOf('tables');
- class_exists('DB_DataObject_Generator') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
- foreach($tables as $table) {
+ foreach ($tables as $table) {
$y = new DB_DataObject_Generator;
- $y->fillTableSchema($x->_database,$table);
+ $y->fillTableSchema($x->_database, $table);
}
- return $_DB_DATAOBJECT['INI'][$x->_database];
+ return $_DB_DATAOBJECT['INI'][$x->_database];
} else {
-
$_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
$_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
}
return true;
}
-
}
// if we are configured to use the proxy..
- if ( !empty($_DB_DATAOBJECT['CONFIG']['proxy']) ) {
+ if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Loading Generator to fetch Schema",1);
+ $this->debug("Loading Generator to fetch Schema", 1);
}
- class_exists('DB_DataObject_Generator') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
$x = new DB_DataObject_Generator;
- $x->fillTableSchema($this->_database,$this->tableName());
+ $x->fillTableSchema($this->_database, $this->tableName());
return true;
}
if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
$schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
- explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
+ explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
}
$_DB_DATAOBJECT['INI'][$this->_database] = array();
foreach ($schemas as $ini) {
- if (file_exists($ini) && is_file($ini)) {
-
+ if (file_exists($ini) && is_file($ini)) {
$_DB_DATAOBJECT['INI'][$this->_database] = array_merge(
$_DB_DATAOBJECT['INI'][$this->_database],
parse_ini_file($ini, true)
);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- if (!is_readable ($ini)) {
- $this->debug("ini file is not readable: $ini","databaseStructure",1);
+ if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
+ if (!is_readable($ini)) {
+ $this->debug("ini file is not readable: $ini", "databaseStructure", 1);
} else {
- $this->debug("Loaded ini file: $ini","databaseStructure",1);
+ $this->debug("Loaded ini file: $ini", "databaseStructure", 1);
}
}
} else {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Missing ini file: $ini","databaseStructure",1);
+ $this->debug("Missing ini file: $ini", "databaseStructure", 1);
}
}
-
}
// are table name lowecased..
if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
- foreach($_DB_DATAOBJECT['INI'][$this->_database] as $k=>$v) {
+ foreach ($_DB_DATAOBJECT['INI'][$this->_database] as $k=>$v) {
// results in duplicate cols.. but not a big issue..
$_DB_DATAOBJECT['INI'][$this->_database][strtolower($k)] = $v;
}
}
- // now have we loaded the structure..
+ // now have we loaded the structure..
if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
return true;
}
// - if not try building it..
if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
- class_exists('DB_DataObject_Generator') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
$x = new DB_DataObject_Generator;
- $x->fillTableSchema($this->_database,$this->tableName());
+ $x->fillTableSchema($this->_database, $this->tableName());
// should this fail!!!???
return true;
}
$this->debug("Cant find database schema: {$this->_database}/{$this->tableName()} \n".
- "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
+ "in links file data: " . print_r($_DB_DATAOBJECT['INI'], true), "databaseStructure", 5);
// we have to die here!! - it causes chaos if we dont (including looping forever!)
- $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);
+ $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);
return false;
-
-
}
* @access public
* @return string The name of the current table
*/
- function tableName()
+ public function tableName()
{
global $_DB_DATAOBJECT;
$args = func_get_args();
* @access public
* @return string The name of the current database
*/
- function database()
+ public function database()
{
$args = func_get_args();
if (count($args)) {
* @param array key=>type array
* @return array (associative)
*/
- function table()
+ public function table()
{
// for temporary storage of database fields..
* @access public
* @return array
*/
- function keys()
+ public function keys()
{
// for temporary storage of database fields..
// note this is not declared as we dont want to bloat the print_r output
* override this to return array(false,false) if table has no real sequence key.
*
* @param string optional the key sequence/autoinc. key
- * @param boolean optional use native increment. default false
+ * @param boolean optional use native increment. default false
* @param false|string optional native sequence name
* @access public
* @return array (column,use_native,sequence_name)
*/
- function sequenceKey()
+ public function sequenceKey()
{
global $_DB_DATAOBJECT;
$keys = $this->keys();
if (!$keys) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]
+ return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]
= array(false,false,false);
}
if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->tableName()])) {
$seqname = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->tableName()];
- if (strpos($seqname,':') !== false) {
- list($usekey,$seqname) = explode(':',$seqname);
+ if (strpos($seqname, ':') !== false) {
+ list($usekey, $seqname) = explode(':', $seqname);
}
- }
+ }
// if the key is not an integer - then it's not a sequence or native
if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,false);
+ return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,false);
}
return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
}
if (is_string($ignore)) {
- $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
+ $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',', $ignore);
}
- if (in_array($this->tableName(),$ignore)) {
+ if (in_array($this->tableName(), $ignore)) {
return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
}
}
// support named sequence keys.. - currently postgres only..
- if ( in_array($dbtype , array('pgsql')) &&
- ($table[$usekey] & DB_DATAOBJECT_INT) &&
+ if (in_array($dbtype, array('pgsql')) &&
+ ($table[$usekey] & DB_DATAOBJECT_INT) &&
isset($realkeys[$usekey]) && strlen($realkeys[$usekey]) > 1) {
return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,true, $realkeys[$usekey]);
}
- if ( in_array($dbtype , array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
- ($table[$usekey] & DB_DATAOBJECT_INT) &&
+ if (in_array($dbtype, array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
+ ($table[$usekey] & DB_DATAOBJECT_INT) &&
isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
) {
return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,true,$seqname);
// if not a native autoinc, and we have not assumed all primary keys are sequence
- if (($realkeys[$usekey] != 'N') &&
+ if (($realkeys[$usekey] != 'N') &&
!empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
return array(false,false,false);
}
* @access private
* @return void
*/
- function _clear_cache()
+ public function _clear_cache()
{
global $_DB_DATAOBJECT;
$class = strtolower(get_class($this));
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Clearing Cache for ".$class,1);
+ $this->debug("Clearing Cache for ".$class, 1);
}
if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
* @return string quoted
*/
- function _quote($str)
+ public function _quote($str)
{
global $_DB_DATAOBJECT;
- return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
+ return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
: $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
* @access private
* @return true | PEAR::error
*/
- function _connect()
+ public function _connect()
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
$this->_loadConfig();
}
- // Set database driver for reference
- $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
+ // Set database driver for reference
+ $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
- // is it already connected ?
+ // 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,
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
+ $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
+ $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code,
+ PEAR_ERROR_DIE
);
-
}
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');
- $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
- ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
+ $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
+ ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
: $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
- if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
- && is_file($this->_database)) {
+ if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
+ && is_file($this->_database)) {
$this->_database = basename($this->_database);
}
- if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase') {
+ if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase') {
$this->_database = substr(basename($this->_database), 0, -4);
}
-
}
// theoretically we have a md5, it's listed in connections and it's not an error.
// so everything is ok!
return true;
-
}
// it's not currently connected!
$this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Checking for database specific ini ('{$this->_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}"])) {
+ if ($this->_database && !empty($options["database_{$this->_database}"])) {
$dsn = $options["database_{$this->_database}"];
- } else if (!empty($options['database'])) {
+ } elseif (!empty($options['database'])) {
$dsn = $options['database'];
-
}
}
if (!$dsn) {
return $this->raiseError(
"No database name / dsn found anywhere",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG,
+ PEAR_ERROR_DIE
);
-
}
if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("USING CACHED CONNECTION", "CONNECT",3);
+ $this->debug("USING CACHED CONNECTION", "CONNECT", 3);
}
if (!$this->_database) {
-
$hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
- $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
- ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
+ $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
+ ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
: $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
- if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
- && is_file($this->_database))
- {
+ if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
+ && is_file($this->_database)) {
$this->_database = basename($this->_database);
}
}
return true;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("NEW CONNECTION TP DATABASE :" .$this->_database , "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);
+ $this->debug(print_r($dsn, true) ." {$this->_database_dsn_md5}", "CONNECT", 3);
}
- // Note this is verbose deliberatly!
+ // Note this is verbose deliberatly!
if ($db_driver == 'DB') {
/* PEAR DB connect */
- // this allows the setings of compatibility on DB
- $db_options = PEAR::getStaticProperty('DB','options');
+ // this allows the setings of compatibility on DB
+ $db_options = PEAR::getStaticProperty('DB', 'options');
require_once 'DB.php';
if ($db_options) {
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn,$db_options);
+ $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn, $db_options);
} else {
$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn);
}
-
} else {
/* assumption is MDB2 */
require_once 'MDB2.php';
- // this allows the setings of compatibility on MDB2
- $db_options = PEAR::getStaticProperty('MDB2','options');
+ // this allows the setings of compatibility on MDB2
+ $db_options = PEAR::getStaticProperty('MDB2', 'options');
$db_options = is_array($db_options) ? $db_options : array();
- $db_options['portability'] = isset($db_options['portability'] )
+ $db_options['portability'] = isset($db_options['portability'])
? $db_options['portability'] : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = MDB2::connect($dsn,$db_options);
-
+ $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = MDB2::connect($dsn, $db_options);
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(print_r($_DB_DATAOBJECT['CONNECTIONS'],true), "CONNECT",5);
+ $this->debug(print_r($_DB_DATAOBJECT['CONNECTIONS'], true), "CONNECT", 5);
}
if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED",5);
+ $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED", 5);
return $this->raiseError(
- "Connect failed, turn on debugging to 5 see why",
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
+ "Connect failed, turn on debugging to 5 see why",
+ $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code,
+ PEAR_ERROR_DIE
);
-
}
if (empty($this->_database)) {
$hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
- $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
- ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
+ $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
+ ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
: $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
- if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
- && is_file($this->_database))
- {
+ if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
+ && is_file($this->_database)) {
$this->_database = basename($this->_database);
}
}
}
/**
- * sends query to database - this is the private one that must work
+ * sends query to database - this is the private one that must work
* - internal functions use this rather than $this->query()
*
* @param string $string
* @access private
* @return mixed none or PEAR_Error
*/
- function _query($string)
+ public function _query($string)
{
global $_DB_DATAOBJECT;
$this->_connect();
$options = $_DB_DATAOBJECT['CONFIG'];
- $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
+ $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
'DB': $_DB_DATAOBJECT['CONFIG']['db_driver'];
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($string,$log="QUERY");
-
+ $this->debug($string, $log="QUERY");
}
if (
(strtolower(substr(trim($string), 0, 6)) != 'select') &&
(strtolower(substr(trim($string), 0, 4)) != 'show') &&
(strtolower(substr(trim($string), 0, 8)) != 'describe')) {
-
$this->debug('Disabling Update as you are in debug mode');
return $this->raiseError("Disabling Update as you are in debug mode", null) ;
-
}
//if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
- // this will only work when PEAR:DB supports it.
- //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
+ // this will only work when PEAR:DB supports it.
+ //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
//}
// some sim
- $t= explode(' ',microtime());
+ $t= explode(' ', microtime());
$_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
for ($tries = 0;$tries < 3;$tries++) {
-
if ($_DB_driver == 'DB') {
-
$result = $DB->query($string);
} else {
- switch (strtolower(substr(trim($string),0,6))) {
+ switch (strtolower(substr(trim($string), 0, 6))) {
case 'insert':
case 'update':
}
// see if we got a failure.. - try again a few times..
- if (!is_object($result) || !is_a($result,'PEAR_Error')) {
+ if (!is_object($result) || !is_a($result, 'PEAR_Error')) {
break;
}
if ($result->getCode() != -14) { // *DB_ERROR_NODBSELECTED
}
- if (is_object($result) && is_a($result,'PEAR_Error')) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($result->toString(), "Query Error",1 );
+ if (is_object($result) && is_a($result, 'PEAR_Error')) {
+ if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
+ $this->debug($result->toString(), "Query Error", 1);
}
$this->N = false;
return $this->raiseError($result);
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $t= explode(' ',microtime());
+ $t= explode(' ', microtime());
$_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
- $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query',1);
+ $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query', 1);
}
- switch (strtolower(substr(trim($string),0,6))) {
+ switch (strtolower(substr(trim($string), 0, 6))) {
case 'insert':
case 'update':
case 'delete':
if ($_DB_driver == 'DB') {
// pear DB specific
- return $DB->affectedRows();
+ return $DB->affectedRows();
}
return $result;
}
// lets hope that copying the result object is OK!
$_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
- $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
+ $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
$this->_DB_resultid = $_DB_resultid;
}
$this->N = 0;
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($result), 'RESULT',5);
+ $this->debug(serialize($result), 'RESULT', 5);
}
if (method_exists($result, 'numRows')) {
if ($_DB_driver == 'DB') {
$this->N = $result->numRows();
//var_dump($this->N);
- if (is_object($this->N) && is_a($this->N,'PEAR_Error')) {
+ if (is_object($this->N) && is_a($this->N, 'PEAR_Error')) {
$this->N = true;
}
$DB->popExpect();
* @access private
* @return string
*/
- function _build_condition($keys, $filter = array(),$negative_filter=array())
+ public function _build_condition($keys, $filter = array(), $negative_filter=array())
{
global $_DB_DATAOBJECT;
$this->_connect();
}
- foreach($keys as $k => $v) {
+ foreach ($keys as $k => $v) {
// index keys is an indexed array
/* these filter checks are a bit suspicious..
- need to check that update really wants to work this way */
continue;
}
- $kSql = $quoteIdentifiers
- ? ( $DB->quoteIdentifier($this->tableName()) . '.' . $DB->quoteIdentifier($k) )
+ $kSql = $quoteIdentifiers
+ ? ($DB->quoteIdentifier($this->tableName()) . '.' . $DB->quoteIdentifier($k))
: "{$this->tableName()}.{$k}";
- if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
+ if (is_object($this->$k) && is_a($this->$k, 'DB_DataObject_Cast')) {
$dbtype = $DB->dsn["phptype"];
- $value = $this->$k->toString($v,$DB);
+ $value = $this->$k->toString($v, $DB);
if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
+ $this->raiseError($value->getMessage(), DB_DATAOBJECT_ERROR_INVALIDARG);
return false;
}
if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
continue;
}
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
+ if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this, $k)) {
$this->whereAdd(" $kSql IS NULL");
continue;
}
if ($v & DB_DATAOBJECT_STR) {
$this->whereAdd(" $kSql = " . $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
+ ($v & DB_DATAOBJECT_BOOL) ?
+ // this is thanks to the braindead idea of postgres to
// use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
+ (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
$this->$k
- )) );
+ )));
continue;
}
if (is_numeric($this->$k)) {
- /**
- * classic factory method for loading a table class
- * usage: $do = DB_DataObject::factory('person')
- * WARNING - this may emit a include error if the file does not exist..
- * use @ to silence it (if you are sure it is acceptable)
- * eg. $do = @DB_DataObject::factory('person')
- *
- * 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
- */
+ /**
+ * classic factory method for loading a table class
+ * usage: $do = DB_DataObject::factory('person')
+ * WARNING - this may emit a include error if the file does not exist..
+ * use @ to silence it (if you are sure it is acceptable)
+ * eg. $do = @DB_DataObject::factory('person')
+ *
+ * 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
+ */
- static function factory($table = '')
+ public static function factory($table = '')
{
global $_DB_DATAOBJECT;
// multi-database support.. - experimental.
$database = '';
- if (strpos( $table,'/') !== false ) {
- list($database,$table) = explode('.',$table, 2);
-
+ if (strpos($table, '/') !== false) {
+ list($database, $table) = explode('.', $table, 2);
}
if (empty($_DB_DATAOBJECT['CONFIG'])) {
}
// no configuration available for database
if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_'.$database])) {
- $do = new DB_DataObject();
- $do->raiseError(
- "unable to find database_{$database} in Configuration, It is required for factory with database"
- , 0, PEAR_ERROR_DIE );
- }
+ $do = new DB_DataObject();
+ $do->raiseError(
+ "unable to find database_{$database} in Configuration, It is required for factory with database",
+ 0,
+ PEAR_ERROR_DIE
+ );
+ }
/*
DB_DATAOBJECT_ERROR_INVALIDARGS);
}
}
-
+
*/
// does this need multi db support??
$cp = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
//print_r($cp);
// multiprefix support.
- $tbl = preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
+ $tbl = preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table));
if (is_array($cp)) {
$class = array();
- foreach($cp as $cpr) {
- $ce = substr(phpversion(),0,1) > 4 ? class_exists($cpr . $tbl,false) : class_exists($cpr . $tbl);
+ foreach ($cp as $cpr) {
+ $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($cpr . $tbl, false) : class_exists($cpr . $tbl);
if ($ce) {
$class = $cpr . $tbl;
break;
}
} else {
$class = $tbl;
- $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
+ $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($class, false) : class_exists($class);
}
$rclass = $ce ? $class : DB_DataObject::_autoloadClass($class, $table);
// proxy = full|light
- if (!$rclass && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
-
- DB_DataObject::debug("FAILED TO Autoload $database.$table - using proxy.","FACTORY",1);
+ if (!$rclass && 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') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
$d = new DB_DataObject;
}
$x = new DB_DataObject_Generator;
- return $x->$proxyMethod( $d->_database, $table);
+ return $x->$proxyMethod($d->_database, $table);
}
if (!$rclass || !class_exists($rclass)) {
$dor = new DB_DataObject();
return $dor->raiseError(
- "factory could not find class " .
- (is_array($class) ? implode(PATH_SEPARATOR, $class) : $class ).
+ "factory could not find class " .
+ (is_array($class) ? implode(PATH_SEPARATOR, $class) : $class).
"from $table",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
}
$ret = new $rclass();
if (!empty($database)) {
- DB_DataObject::debug("Setting database to $database","FACTORY",1);
+ DB_DataObject::debug("Setting database to $database", "FACTORY", 1);
$ret->database($database);
}
return $ret;
* @access private
* @return string classname on Success
*/
- function _autoloadClass($class, $table=false)
+ public function _autoloadClass($class, $table=false)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
- $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
+ $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
'' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
- $table = $table ? $table : substr($class,strlen($class_prefix));
+ $table = $table ? $table : substr($class, strlen($class_prefix));
// only include the file if it exists - and barf badly if it has parse errors :)
if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
switch (true) {
- case (strpos($cl ,'%s') !== false):
- $file = sprintf($cl , preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
+ case (strpos($cl, '%s') !== false):
+ $file = sprintf($cl, preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table)));
break;
- case (strpos($cl , PATH_SEPARATOR) !== false):
+ case (strpos($cl, PATH_SEPARATOR) !== false):
$file = array();
- foreach(explode(PATH_SEPARATOR, $cl ) as $p) {
- $file[] = $p .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
+ foreach (explode(PATH_SEPARATOR, $cl) as $p) {
+ $file[] = $p .'/'.preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table)).".php";
}
break;
default:
- $file = $cl .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
+ $file = $cl .'/'.preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table)).".php";
break;
}
$file = is_array($file) ? $file : array($file);
$search = implode(PATH_SEPARATOR, $file);
- foreach($file as $f) {
- foreach(explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
+ foreach ($file as $f) {
+ foreach (explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
$ff = empty($p) ? $f : "$p/$f";
if (file_exists($ff)) {
$dor->raiseError(
"autoload:Could not find class " . implode(',', $cls) .
" using class_location value :" . $search .
- " using include_path value :" . ini_get('include_path'),
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ " using include_path value :" . ini_get('include_path'),
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
}
$ce = false;
- foreach($cls as $c) {
- $ce = substr(phpversion(),0,1) > 4 ? class_exists($c,false) : class_exists($c);
+ foreach ($cls as $c) {
+ $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($c, false) : class_exists($c);
if ($ce) {
$class = $c;
break;
if (!$ce) {
$dor = new DB_DataObject();
$dor->raiseError(
- "autoload:Could not autoload " . implode(',', $cls) ,
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ "autoload:Could not autoload " . implode(',', $cls),
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
return $class;
* @access private
* @var boolean | array
*/
- var $_link_loaded = false;
+ public $_link_loaded = false;
/**
* Get the links associate array as defined by the links.ini file.
- *
*
- * Experimental... -
+ *
+ * Experimental... -
* Should look a bit like
* [local_col_name] => "related_tablename:related_col_name"
- *
+ *
* @param array $new_links optional - force update of the links for this table
* You probably want to restore it to it's original state after,
* as modifying here does it for the whole PHP request.
- *
- * @return array|null
+ *
+ * @return array|null
* array = if there are links defined for this table.
* empty array - if there is a links.ini file, but no links on this table
* false - if no links.ini exists for this database (hence try auto_links).
* @see DB_DataObject::getLinks(), DB_DataObject::getLink()
*/
- function links()
+ public function links()
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
if ($args = func_get_args()) {
// an associative array was specified, that updates the current
// schema... - be careful doing this
- if (empty( $lcfg[$this->_database])) {
+ if (empty($lcfg[$this->_database])) {
$lcfg[$this->_database] = array();
}
$lcfg[$this->_database][$this->tableName()] = $args[0];
-
}
// loaded and available.
if (isset($lcfg[$this->_database][$this->tableName()])) {
return $lcfg[$this->_database][$this->tableName()];
}
- // loaded
+ // loaded
if (isset($lcfg[$this->_database])) {
// either no file, or empty..
return $lcfg[$this->_database] === false ? null : array();
array() ;
// if ini_* is set look there instead.
- // and support multiple locations.
+ // and support multiple locations.
if (isset($cfg["ini_{$this->_database}"])) {
$schemas = is_array($cfg["ini_{$this->_database}"]) ?
$cfg["ini_{$this->_database}"] :
- explode(PATH_SEPARATOR,$cfg["ini_{$this->_database}"]);
+ explode(PATH_SEPARATOR, $cfg["ini_{$this->_database}"]);
}
// default to not available.
$lcfg[$this->_database] = false;
foreach ($schemas as $ini) {
-
$links = isset($cfg["links_{$this->_database}"]) ?
$cfg["links_{$this->_database}"] :
- str_replace('.ini','.links.ini',$ini);
+ str_replace('.ini', '.links.ini', $ini);
// file really exists..
if (!file_exists($links) || !is_file($links)) {
if (!empty($cfg['debug'])) {
- $this->debug("Missing links.ini file: $links","links",1);
+ $this->debug("Missing links.ini file: $links", "links", 1);
}
continue;
}
if (!empty($cfg['debug'])) {
- $this->debug("Loaded links.ini file: $links","links",1);
+ $this->debug("Loaded links.ini file: $links", "links", 1);
}
-
}
if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
- foreach($lcfg[$this->_database] as $k=>$v) {
-
+ foreach ($lcfg[$this->_database] as $k=>$v) {
$nk = strtolower($k);
// results in duplicate cols.. but not a big issue..
$lcfg[$this->_database][$nk] = isset($lcfg[$this->_database][$nk])
? $lcfg[$this->_database][$nk] : array();
- foreach($v as $kk =>$vv) {
+ foreach ($v as $kk =>$vv) {
//var_Dump($vv);exit;
$vv =explode(':', $vv);
$vv[0] = strtolower($vv[0]);
$lcfg[$this->_database][$nk][$kk] = implode(':', $vv);
}
-
-
}
}
//echo '<PRE>';print_r($lcfg);exit;
* get:
* $obj = $do->link('company_id');
* $obj = $do->link(array('local_col', 'linktable:linked_col'));
- *
+ *
* set:
* $do->link('company_id',0);
* $do->link('company_id',$obj);
* $this->link(array('company_id','company:id'), func_get_args());
* }
*
- *
+ *
*
* @param mixed $link_spec link specification (normally a string)
* uses similar rules to joinAdd() array argument.
* @access public
* @return mixed true or false on setting, object on getting
*/
- function link($field, $set_args = array())
+ public function link($field, $set_args = array())
{
require_once 'DB/DataObject/Links.php';
$l = new DB_DataObject_Links($this);
- return $l->link($field,$set_args) ;
-
+ return $l->link($field, $set_args) ;
}
- /**
+ /**
* load related objects
*
* Generally not recommended to use this.
* @access public
* @return boolean , true on success
*/
- function getLinks($format = '_%s')
+ public function getLinks($format = '_%s')
{
require_once 'DB/DataObject/Links.php';
- $l = new DB_DataObject_Links($this);
+ $l = new DB_DataObject_Links($this);
return $l->applyLinks($format);
-
}
/**
- * deprecited : @use link()
+ * deprecited : @use link()
*/
- function getLink($row, $table = null, $link = false)
+ public function getLink($row, $table = null, $link = false)
{
require_once 'DB/DataObject/Links.php';
$l = new DB_DataObject_Links($this);
return $l->getLink($row, $table === null ? false: $table, $link);
-
-
}
/**
* @param string $column - either column or column.xxxxx
* @param string $table - name of table to look up value in
* @return array - array of results (empty array on failure)
- *
+ *
* Example - Getting the related objects
- *
+ *
* $person = new DataObjects_Person;
* $person->get(12);
* $children = $person->getLinkArray('children');
- *
+ *
* echo 'There are ', count($children), ' descendant(s):<br />';
* foreach ($children as $child) {
* echo $child->name, '<br />';
* }
- *
+ *
*/
- function getLinkArray($row, $table = null)
+ public function getLinkArray($row, $table = null)
{
require_once 'DB/DataObject/Links.php';
$l = new DB_DataObject_Links($this);
return $l->getLinkArray($row, $table === null ? false: $table);
-
}
- /**
- * unionAdd - adds another dataobject to this, building a unioned query.
- *
- * usage:
- * $doTable1 = DB_DataObject::factory("table1");
- * $doTable2 = DB_DataObject::factory("table2");
- *
- * $doTable1->selectAdd();
- * $doTable1->selectAdd("col1,col2");
- * $doTable1->whereAdd("col1 > 100");
- * $doTable1->orderBy("col1");
- *
- * $doTable2->selectAdd();
- * $doTable2->selectAdd("col1, col2");
- * $doTable2->whereAdd("col2 = 'v'");
- *
- * $doTable1->unionAdd($doTable2);
- * $doTable1->find();
- *
- * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
- *
- *
- * @param $obj object|false the union object or false to reset
- * @param optional $is_all string 'ALL' to do all.
- * @returns $obj object|array the added object, or old list if reset.
- */
+ /**
+ * unionAdd - adds another dataobject to this, building a unioned query.
+ *
+ * usage:
+ * $doTable1 = DB_DataObject::factory("table1");
+ * $doTable2 = DB_DataObject::factory("table2");
+ *
+ * $doTable1->selectAdd();
+ * $doTable1->selectAdd("col1,col2");
+ * $doTable1->whereAdd("col1 > 100");
+ * $doTable1->orderBy("col1");
+ *
+ * $doTable2->selectAdd();
+ * $doTable2->selectAdd("col1, col2");
+ * $doTable2->whereAdd("col2 = 'v'");
+ *
+ * $doTable1->unionAdd($doTable2);
+ * $doTable1->find();
+ *
+ * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
+ *
+ *
+ * @param $obj object|false the union object or false to reset
+ * @param optional $is_all string 'ALL' to do all.
+ * @returns $obj object|array the added object, or old list if reset.
+ */
- function unionAdd($obj,$is_all= '')
+ public function unionAdd($obj, $is_all= '')
{
if ($obj === false) {
$ret = $this->_query['unions'];
* @access private
* @var string
*/
- var $_join = '';
+ public $_join = '';
/**
* joinAdd - adds another dataobject to this, building a joined query.
* if array has 3 args, then second is assumed to be the linked dataobject.
*
* @param optional $joinType string | array
- * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
- * just select ... from a,b,c with no join and
+ * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
+ * just select ... from a,b,c with no join and
* links are added as where items.
- *
+ *
* If second Argument is array, it is assumed to be an associative
* array with arguments matching below = eg.
* 'joinType' => 'INNER',
* @param optional $joinAs string if you want to select the table as anther name
* useful when you want to select multiple columsn
* from a secondary table.
-
+
* @param optional $joinCol string The column on This objects table to match (needed
- * if this table links to the child object in
+ * if this table links to the child object in
* multiple places eg.
* user->friend (is a link to another user)
* user->mother (is a link to another user..)
* optional 'useWhereAsOn' bool default false;
* convert the where argments from the object being added
* into ON arguments.
- *
- *
+ *
+ *
* @return none
* @access public
* @author Stijn de Reede <sjr@gmx.co.uk>
*/
- function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
+ public function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
{
global $_DB_DATAOBJECT;
if ($obj === false) {
$joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
$joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
}
- // support for array as first argument
+ // support for array as first argument
// this assumes that you dont have a links.ini for the specified table.
// and it doesnt exist as am extended dataobject!! - experimental.
$ofield = $obj[2];
$obj = $obj[1];
} else {
- list($toTable,$ofield) = explode(':',$obj[1]);
+ list($toTable, $ofield) = explode(':', $obj[1]);
$obj = is_string($toTable) ? DB_DataObject::factory($toTable) : $toTable;
- if (!$obj || !is_object($obj) || is_a($obj,'PEAR_Error')) {
+ if (!$obj || !is_object($obj) || is_a($obj, 'PEAR_Error')) {
$obj = new DB_DataObject;
$obj->__table = $toTable;
}
$items = array();
}
- if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
- return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
+ if (!is_object($obj) || !is_a($obj, 'DB_DataObject')) {
+ return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA, PEAR_ERROR_DIE);
}
/* make sure $this->_database is set. */
$this->_connect();
// or standard way.
// link contains this_column = linked_table:linked_column
foreach ($links as $k => $linkVar) {
-
if (!is_array($linkVar)) {
$linkVar = array($linkVar);
}
- foreach($linkVar as $v) {
+ foreach ($linkVar as $v) {
$tfield = $k;
$ofield = $ar[1];
break;
- }
+ }
continue;
-
- }
+ }
$tfield = $k;
$ofield = $ar[1];
break;
-
}
}
}
- /* look up the links for obj table */
+ /* look up the links for obj table */
//print_r($obj->links());
if (!$ofield && ($olinks = $obj->links())) {
-
foreach ($olinks as $k => $linkVar) {
/* link contains {this column} = array ( {linked table}:{linked column} )*/
if (!is_array($linkVar)) {
$linkVar = array($linkVar);
}
- foreach($linkVar as $v) {
+ foreach ($linkVar as $v) {
/* link contains {this column} = {linked table}:{linked column} */
$ar = explode(':', $v);
// Feature Request #4266 - Allow joins with multiple keys
- $links_key_array = strpos($k,',');
+ $links_key_array = strpos($k, ',');
if ($links_key_array !== false) {
$k = explode(',', $k);
}
- $ar_array = strpos($ar[1],',');
+ $ar_array = strpos($ar[1], ',');
if ($ar_array !== false) {
$ar[1] = explode(',', $ar[1]);
}
// not sure if 1:1 table could cause probs here..
if ($joinCol !== false) {
- $this->raiseError(
+ $this->raiseError(
"joinAdd: You cannot target a join column in the " .
- "'link from' table ({$obj->tableName()}). " .
+ "'link from' table ({$obj->tableName()}). " .
"Either remove the fourth argument to joinAdd() ".
"({$joinCol}), or alter your links.ini file.",
- DB_DATAOBJECT_ERROR_NODATA);
+ DB_DATAOBJECT_ERROR_NODATA
+ );
return false;
}
$ofield = $k;
$tfield = $ar[1];
break;
-
}
}
}
if (($ofield === false) && $joinCol) {
$ofield = $joinCol;
$tfield = $joinCol;
-
}
/* did I find a conneciton between them? */
if ($ofield === false) {
$this->raiseError(
"joinAdd: {$obj->tableName()} has no link with {$this->tableName()}",
- DB_DATAOBJECT_ERROR_NODATA);
+ DB_DATAOBJECT_ERROR_NODATA
+ );
return false;
}
$joinType = strtoupper($joinType);
$options = $_DB_DATAOBJECT['CONFIG'];
// not sure how portable adding database prefixes is..
- $objTable = $quoteIdentifiers ?
- $DB->quoteIdentifier($obj->tableName()) :
+ $objTable = $quoteIdentifiers ?
+ $DB->quoteIdentifier($obj->tableName()) :
$obj->tableName() ;
$dbPrefix = '';
- if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
+ if (strlen($obj->_database) && in_array($DB->dsn['phptype'], array('mysql','mysqli'))) {
$dbPrefix = ($quoteIdentifiers
? $DB->quoteIdentifier($obj->_database)
- : $obj->_database) . '.';
+ : $obj->_database) . '.';
}
- // if they are the same, then dont add a prefix...
+ // if they are the same, then dont add a prefix...
if ($obj->_database == $this->_database) {
- $dbPrefix = '';
+ $dbPrefix = '';
}
// as far as we know only mysql supports database prefixes..
// prefixing the database name is now the default behaviour,
// as it enables joining mutiple columns from multiple databases...
- // prefix database (quoted if neccessary..)
+ // prefix database (quoted if neccessary..)
$objTable = $dbPrefix . $objTable;
$cond = '';
// it obvioulsy cant work out what child elements might exist...
// until we get on the fly querying of tables..
// note: we have already checked that it is_a(db_dataobject earlier)
- if ( strtolower(get_class($obj)) != 'db_dataobject') {
+ if (strtolower(get_class($obj)) != 'db_dataobject') {
- // now add where conditions for anything that is set in the object
+ // now add where conditions for anything that is set in the object
if (!$items) {
$this->raiseError(
- "joinAdd: No table definition for {$obj->tableName()}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ "joinAdd: No table definition for {$obj->tableName()}",
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
|| strtolower($options['disable_null_strings']) !== 'full' ;
- foreach($items as $k => $v) {
+ foreach ($items as $k => $v) {
if (!isset($obj->$k) && $ignore_null) {
continue;
}
$kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
- if (DB_DataObject::_is_null($obj,$k)) {
- $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
- continue;
+ if (DB_DataObject::_is_null($obj, $k)) {
+ $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
+ continue;
}
if ($v & DB_DATAOBJECT_STR) {
$obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
+ ($v & DB_DATAOBJECT_BOOL) ?
+ // this is thanks to the braindead idea of postgres to
// use t/f for boolean.
- (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
+ (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :
$obj->$k
)));
continue;
continue;
}
- if (is_object($obj->$k) && is_a($obj->$k,'DB_DataObject_Cast')) {
- $value = $obj->$k->toString($v,$DB);
+ if (is_object($obj->$k) && is_a($obj->$k, 'DB_DataObject_Cast')) {
+ $value = $obj->$k->toString($v, $DB);
if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
+ $this->raiseError($value->getMessage(), DB_DATAOBJECT_ERROR_INVALIDARG);
return false;
- }
+ }
$obj->whereAdd("{$joinAs}.{$kSql} = $value");
continue;
}
if ($this->_query === false) {
$this->raiseError(
"joinAdd can not be run from a object that has had a query run on it,
- clone the object or create a new one and use setFrom()",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
+ clone the object or create a new one and use setFrom()",
+ DB_DATAOBJECT_ERROR_INVALIDARGS
+ );
return false;
}
}
// and finally merge the whereAdd from the child..
if ($obj->_query['condition']) {
- $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
+ $cond = preg_replace('/^\sWHERE/i', '', $obj->_query['condition']);
if (!$useWhereAsOn) {
$this->whereAdd($cond);
// postgres allows nested queries, with ()'s
// not sure what the results are with other databases..
// may be unpredictable..
- if (in_array($DB->dsn["phptype"],array('pgsql'))) {
+ if (in_array($DB->dsn["phptype"], array('pgsql'))) {
$objTable = "($objTable {$obj->_join})";
} else {
$appendJoin = $obj->_join;
if ($quoteIdentifiers) {
$joinAs = $DB->quoteIdentifier($joinAs);
- $table = $DB->quoteIdentifier($table);
+ $table = $DB->quoteIdentifier($table);
$ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
- $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
+ $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
}
// add database prefix if they are different databases
// join table a AS b - is only supported by a few databases and is probably not needed
// , however since it makes the whole Statement alot clearer we are leaving it in
// for those databases.
- $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
+ $fullJoinAs = in_array($DB->dsn["phptype"], array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" : $joinAs;
} else {
- // if
+ // if
$joinAs = $dbPrefix . $joinAs;
}
switch ($joinType) {
case 'INNER':
- case 'LEFT':
+ case 'LEFT':
case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
// Feature Request #4266 - Allow joins with multiple keys
$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) {
- $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
- }
- else {
- $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
- }
+ $key_count = count($ofield);
+ for ($i = 0; $i < $key_count; $i++) {
+ if ($i == 0) {
+ $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
+ } else {
+ $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
+ }
}
$jadd .= ' ' . $appendJoin . ' ';
} else {
- $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
+ $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
}
// jadd avaliable for debugging join build.
//echo $jadd ."\n";
return true;
-
}
/**
- * autoJoin - using the links.ini file, it builds a query with all the joins
- * usage:
+ * autoJoin - using the links.ini file, it builds a query with all the joins
+ * usage:
* $x = DB_DataObject::factory('mytable');
* $x->autoJoin();
- * $x->get(123);
+ * $x->get(123);
* will result in all of the joined data being added to the fetched object..
- *
+ *
* $x = DB_DataObject::factory('mytable');
* $x->autoJoin();
* $ar = $x->fetchAll();
* will result in an array containing all the data from the table, and any joined tables..
- *
+ *
* $x = DB_DataObject::factory('mytable');
* $jdata = $x->autoJoin();
* $x->selectAdd(); //reset..
* if (!isset($jdata[$c])) continue; // ignore columns not available..
* $x->selectAdd( $jdata[$c] . ' as ' . $c);
* }
- * $ar = $x->fetchAll();
+ * $ar = $x->fetchAll();
* will result in only the columns requested being fetched...
*
*
* array( 'person_id' => 'person:id', .... )
* include Array of columns to include
* distinct Array of distinct columns.
- *
+ *
* @return array info about joins
* cols => map of resulting {joined_tablename}.{joined_table_column_name}
* join_names => map of resulting {join_name_as}.{joined_table_column_name}
* count => the column to count on.
* @access public
*/
- function autoJoin($cfg = array())
+ public function autoJoin($cfg = array())
{
global $_DB_DATAOBJECT;
//var_Dump($cfg);exit;
$pre_links = $this->links();
if (!empty($cfg['links'])) {
- $this->links(array_merge( $pre_links , $cfg['links']));
+ $this->links(array_merge($pre_links, $cfg['links']));
}
- $map = $this->links( );
+ $map = $this->links();
$this->databaseStructure();
$dbstructure = $_DB_DATAOBJECT['INI'][$this->_database];
$keys = array_keys($tabdef);
if (!empty($cfg['exclude'])) {
- $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
+ $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
}
if (!empty($cfg['include'])) {
-
- $keys = array_intersect($keys, $cfg['include']);
+ $keys = array_intersect($keys, $cfg['include']);
}
$selectAs = array();
// reset the columsn?
$cols = array();
- //echo '<PRE>' ;print_r($xx);exit;
- foreach($keys as $c) {
+ //echo '<PRE>' ;print_r($xx);exit;
+ foreach ($keys as $c) {
//var_dump($c);
- if ( $cfg['distinct'] == $c) {
+ if ($cfg['distinct'] == $c) {
$has_distinct = 'DISTINCT( ' . $this->tableName() .'.'. $c .') as ' . $c;
$ret['count'] = 'DISTINCT ' . $this->tableName() .'.'. $c .'';
continue;
}
// cols is in our filtered keys...
$cols = $c;
-
}
// apply our filtered version, which excludes the distinct column.
$selectAs = empty($cols) ? array() : array(array(array( $cols) , '%s', false)) ;
-
-
-
- }
+ }
- foreach($keys as $k) {
+ foreach ($keys as $k) {
$ret['cols'][$k] = $this->tableName(). '.' . $k;
}
- foreach($map as $ocl=>$info) {
-
- list($tab,$col) = explode(':', $info);
+ foreach ($map as $ocl=>$info) {
+ list($tab, $col) = explode(':', $info);
// what about multiple joins on the same table!!!
// if links point to a table that does not exist - ignore.
if (!empty($cfg['exclude'])) {
$keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
- foreach($keys as $k) {
+ foreach ($keys as $k) {
if (in_array($ocl.'_'.$k, $cfg['exclude'])) {
$keys = array_diff($keys, $k); // removes the k..
}
}
-
}
if (!empty($cfg['include'])) {
// include will basically be BASECOLNAME_joinedcolname
$nkeys = array();
- foreach($keys as $k) {
- if (in_array( sprintf($ocl.'_%s', $k), $cfg['include'])) {
+ foreach ($keys as $k) {
+ if (in_array(sprintf($ocl.'_%s', $k), $cfg['include'])) {
$nkeys[] = $k;
}
}
continue;
}
// got distinct, and not yet found it..
- if (!$has_distinct && !empty($cfg['distinct'])) {
+ if (!$has_distinct && !empty($cfg['distinct'])) {
$cols = array();
- foreach($keys as $c) {
+ foreach ($keys as $c) {
$tn = sprintf($ocl.'_%s', $c);
- if ( $tn == $cfg['distinct']) {
-
+ if ($tn == $cfg['distinct']) {
$has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$c .') as ' . $tn ;
$ret['count'] = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$c;
- // var_dump($this->countWhat );
+ // var_dump($this->countWhat );
continue;
}
$cols[] = $c;
-
}
if (!empty($cols)) {
$selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
}
-
} else {
$selectAs[] = array($keys, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
}
- foreach($keys as $k) {
+ foreach ($keys as $k) {
$ret['cols'][sprintf('%s_%s', $ocl, $k)] = $tab.'.'.$k;
- $ret['join_names'][sprintf('%s_%s', $ocl, $k)] = sprintf('join_%s_%s.%s',$ocl, $col, $k);
+ $ret['join_names'][sprintf('%s_%s', $ocl, $k)] = sprintf('join_%s_%s.%s', $ocl, $col, $k);
}
-
}
// fill in the select details..
- $this->selectAdd();
+ $this->selectAdd();
if ($has_distinct) {
$this->selectAdd($has_distinct);
}
- foreach($selectAs as $ar) {
+ foreach ($selectAs as $ar) {
$this->selectAs($ar[0], $ar[1], $ar[2]);
}
// restore links..
- $this->links( $pre_links );
+ $this->links($pre_links);
return $ret;
-
}
/**
* Factory method for calling DB_DataObject_Cast
*
* if used with 1 argument DB_DataObject_Cast::sql($value) is called
- *
+ *
* if used with 2 arguments DB_DataObject_Cast::$value($callvalue) is called
* valid first arguments are: blob, string, date, sql
- *
+ *
* eg. $member->updated = $member->sqlValue('NOW()');
- *
- *
+ *
+ *
* might handle more arguments for escaping later...
- *
+ *
*
* @param string $value (or type if used with 2 arguments)
* @param string $callvalue (optional) used with date/null etc..
*/
- function sqlValue($value)
+ public function sqlValue($value)
{
$method = 'sql';
if (func_num_args() == 2) {
}
require_once 'DB/DataObject/Cast.php';
return call_user_func(array('DB_DataObject_Cast', $method), $value);
-
}
* @access public
* @return true on success or array of key=>setValue error message
*/
- function setFrom($from, $format = '%s', $skipEmpty=false)
+ public function setFrom($from, $format = '%s', $skipEmpty=false)
{
global $_DB_DATAOBJECT;
$keys = $this->keys();
if (!$items) {
$this->raiseError(
- "setFrom:Could not find table definition for {$this->tableName()}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ "setFrom:Could not find table definition for {$this->tableName()}",
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return;
}
$overload_return = array();
foreach (array_keys($items) as $k) {
- if (in_array($k,$keys)) {
+ if (in_array($k, $keys)) {
continue; // dont overwrite keys
}
if (!$k) {
continue; // ignore empty keys!!! what
}
- $chk = is_object($from) &&
- (version_compare(phpversion(), "5.1.0" , ">=") ?
- property_exists($from, sprintf($format,$k)) : // php5.1
- array_key_exists( sprintf($format,$k), get_class_vars($from)) //older
+ $chk = is_object($from) &&
+ (
+ version_compare(phpversion(), "5.1.0", ">=") ?
+ property_exists($from, sprintf($format, $k)) : // php5.1
+ array_key_exists(sprintf($format, $k), get_class_vars($from)) //older
);
- // if from has property ($format($k)
+ // if from has property ($format($k)
if ($chk) {
$kk = (strtolower($k) == 'from') ? '_from' : $k;
- if (method_exists($this,'set'.$kk)) {
- $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
+ if (method_exists($this, 'set'.$kk)) {
+ $ret = $this->{'set'.$kk}($from->{sprintf($format, $k)});
if (is_string($ret)) {
$overload_return[$k] = $ret;
}
continue;
}
- $this->$k = $from->{sprintf($format,$k)};
+ $this->$k = $from->{sprintf($format, $k)};
continue;
}
continue;
}
- if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
+ if (empty($from[sprintf($format, $k)]) && $skipEmpty) {
continue;
}
- if (!isset($from[sprintf($format,$k)]) && !DB_DataObject::_is_null($from, sprintf($format,$k))) {
+ if (!isset($from[sprintf($format, $k)]) && !DB_DataObject::_is_null($from, sprintf($format, $k))) {
continue;
}
$kk = (strtolower($k) == 'from') ? '_from' : $k;
- if (method_exists($this,'set'. $kk)) {
- $ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
+ if (method_exists($this, 'set'. $kk)) {
+ $ret = $this->{'set'.$kk}($from[sprintf($format, $k)]);
if (is_string($ret)) {
$overload_return[$k] = $ret;
}
continue;
}
- $val = $from[sprintf($format,$k)];
+ $val = $from[sprintf($format, $k)];
if (is_a($val, 'DB_DataObject_Cast')) {
$this->$k = $val;
continue;
if (is_object($val) || is_array($val)) {
continue;
}
- $ret = $this->fromValue($k,$val);
- if ($ret !== true) {
+ $ret = $this->fromValue($k, $val);
+ if ($ret !== true) {
$overload_return[$k] = 'Not A Valid Value';
}
//$this->$k = $from[sprintf($format,$k)];
* @return array of key => value for row
*/
- function toArray($format = '%s', $hideEmpty = false)
+ public function toArray($format = '%s', $hideEmpty = false)
{
global $_DB_DATAOBJECT;
$format = $format == '%s' ? false : $format;
$ret = array();
- $rf = ($this->_resultFields !== false) ? $this->_resultFields :
+ $rf = ($this->_resultFields !== false) ? $this->_resultFields :
(isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ?
$_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
(($hideEmpty === 0) ? $rf : array_merge($rf, $this->table())) :
$this->table();
- foreach($ar as $k=>$v) {
-
+ foreach ($ar as $k=>$v) {
if (!isset($this->$k)) {
if (!$hideEmpty) {
- $ret[$format === false ? $k : sprintf($format,$k)] = '';
+ $ret[$format === false ? $k : sprintf($format, $k)] = '';
}
continue;
}
// call the overloaded getXXXX() method. - except getLink and getLinks
- if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
- $ret[$format === false ? $k : sprintf($format,$k)] = $this->{'get'.$k}();
+ if (method_exists($this, 'get'.$k) && !in_array(strtolower($k), array('links','link'))) {
+ $ret[$format === false ? $k : sprintf($format, $k)] = $this->{'get'.$k}();
continue;
}
// should this call toValue() ???
- $ret[$format === false ? $k : sprintf($format,$k)] = $this->$k;
+ $ret[$format === false ? $k : sprintf($format, $k)] = $this->$k;
}
if (!$this->_link_loaded) {
return $ret;
}
- foreach($this->_link_loaded as $k) {
- $ret[$format === false ? $k : sprintf($format,$k)] = $this->$k->toArray();
-
+ foreach ($this->_link_loaded as $k) {
+ $ret[$format === false ? $k : sprintf($format, $k)] = $this->$k->toArray();
}
return $ret;
* Note: This was always intended as a simple validation routine.
* It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
*
- * This should be moved to another class: DB_DataObject_Validate
+ * This should be moved to another class: DB_DataObject_Validate
* FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
*
* Usage:
* Logic:
* - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
* - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
- * These methods should return
+ * These methods should return
* true = everything ok
* false|object = something is wrong!
- *
+ *
* - This method loads and uses the PEAR Validate Class.
*
*
* @access public
* @return array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
*/
- function validate()
+ public function validate()
{
global $_DB_DATAOBJECT;
require_once 'Validate.php';
$ret = array();
$seq = $this->sequenceKey();
$options = $_DB_DATAOBJECT['CONFIG'];
- foreach($table as $key => $val) {
+ foreach ($table as $key => $val) {
// call user defined validation always...
}
- if (DB_DataObject::_is_null($this, $key)) {
+ if (DB_DataObject::_is_null($this, $key)) {
if ($val & DB_DATAOBJECT_NOTNULL) {
$this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
$ret[$key] = false;
}
// dont try and validate cast objects - assume they are problably ok..
- if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
+ if (is_object($this->$key) && is_a($this->$key, 'DB_DataObject_Cast')) {
continue;
}
// at this point if you have set something to an object, and it's not expected
- // the Validate will probably break!!... - rightly so! (your design is broken,
+ // the Validate will probably break!!... - rightly so! (your design is broken,
// so issuing a runtime error like PEAR_Error is probably not appropriate..
switch (true) {
// todo: date time.....
case ($val & DB_DATAOBJECT_STR):
$ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
- continue;
+ break;
case ($val & DB_DATAOBJECT_INT):
$ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
- continue;
+ break;
}
}
// if any of the results are false or an object (eg. PEAR_Error).. then return the array..
* @access public
* @return object The DB connection
*/
- function getDatabaseConnection()
+ public function getDatabaseConnection()
{
global $_DB_DATAOBJECT;
* @return object The DB result object
*/
- function getDatabaseResult()
+ public function getDatabaseResult()
{
global $_DB_DATAOBJECT;
$this->_connect();
* - enables setCOLNAME/getCOLNAME
* if you define a set/get method for the item it will be called.
* otherwise it will just return/set the value.
- * NOTE this currently means that a few Names are NO-NO's
+ * NOTE this currently means that a few Names are NO-NO's
* eg. links,link,linksarray, from, Databaseconnection,databaseresult
*
- * note
+ * note
* - set is automatically called by setFrom.
* - get is automatically called by toArray()
- *
+ *
* setters return true on success. = strings on failure
* getters return the value!
*
- * this fires off trigger_error - if any problems.. pear_error,
+ * this fires off trigger_error - if any problems.. pear_error,
* has problems with 4.3.2RC2 here
*
* @access public
*/
- function _call($method,$params,&$return) {
+ public function _call($method, $params, &$return)
+ {
//$this->debug("ATTEMPTING OVERLOAD? $method");
// ignore constructors : - mm
if (strtolower($method) == strtolower(get_class($this))) {
return true;
}
- $type = strtolower(substr($method,0,3));
+ $type = strtolower(substr($method, 0, 3));
$class = get_class($this);
if (($type != 'set') && ($type != 'get')) {
return false;
// deal with naming conflick of setFrom = this is messy ATM!
if (strtolower($method) == 'set_from') {
- $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
+ $return = $this->toValue('from', isset($params[0]) ? $params[0] : null);
return true;
}
- $element = substr($method,3);
+ $element = substr($method, 3);
// dont you just love php's case insensitivity!!!!
$array = array_keys($reflection->getdefaultProperties());
}
- if (!in_array($element,$array)) {
+ if (!in_array($element, $array)) {
// munge case
- foreach($array as $k) {
+ foreach ($array as $k) {
$case[strtolower($k)] = $k;
}
- if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
- trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
+ if ((substr(phpversion(), 0, 1) == 5) && isset($case[strtolower($element)])) {
+ trigger_error("PHP5 set/get calls should match the case of the variable", E_USER_WARNING);
$element = strtolower($element);
}
// does it really exist?
if (!isset($case[$element])) {
- return false;
+ return false;
}
// use the mundged case
$element = $case[$element]; // real case !
if ($type == 'get') {
- $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
+ $return = $this->toValue($element, isset($params[0]) ? $params[0] : null);
return true;
}
$return = $this->fromValue($element, $params[0]);
return true;
-
-
}
* standard set* implementation.
*
* takes data and uses it to set dates/strings etc.
- * normally called from __call..
+ * normally called from __call..
*
* Current supports
* date = using (standard time format, or unixtimestamp).... so you could create a method :
* function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
*
- * time = using strtotime
+ * time = using strtotime
* datetime = using same as date - accepts iso standard or unixtimestamp.
* string = typecast only..
- *
+ *
* TODO: add formater:: eg. d/m/Y for date! ???
*
* @param string column of database
* @param mixed value to assign
*
* @return true| false (False on error)
- * @access public
+ * @access public
* @see DB_DataObject::_call
*/
- function fromValue($col,$value)
+ public function fromValue($col, $value)
{
global $_DB_DATAOBJECT;
$options = $_DB_DATAOBJECT['CONFIG'];
switch (true) {
// set to null and column is can be null...
case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
- case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
+ case (is_object($value) && is_a($value, 'DB_DataObject_Cast')):
$this->$col = $value;
return true;
// fail on setting null on a not null field..
- case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value,false)):
+ case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value, false)):
return false;
if (!$value) {
$this->$col = '';
- return true;
+ return true;
}
if (is_numeric($value)) {
- $this->$col = date('Y-m-d',$value);
+ $this->$col = date('Y-m-d', $value);
return true;
}
$guess = strtotime($value);
if ($guess != -1) {
- $this->$col = date('H:i:s', $guess);
+ $this->$col = date('H:i:s', $guess);
return $return = true;
}
// otherwise an error in type...
$this->$col = $value;
return true;
}
-
-
-
}
- /**
+ /**
* standard get* implementation.
*
* with formaters..
- * supported formaters:
- * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
+ * supported formaters:
+ * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
* numbers : %02d (eg. sprintf)
* NOTE you will get unexpected results with times like 0000-00-00 !!!
*
*
- *
+ *
* @param string column of database
* @param format foramt
*
* @return true Description
- * @access public
+ * @access public
* @see DB_DataObject::_call(),strftime(),Date::format()
*/
- function toValue($col,$format = null)
+ public function toValue($col, $format = null)
{
if (is_null($format)) {
return $this->$col;
case ($cols[$col] & DB_DATAOBJECT_DATE):
if (!$this->$col) {
return '';
- }
+ }
$guess = strtotime($this->$col);
if ($guess != -1) {
- return strftime($format,$guess);
+ return strftime($format, $guess);
}
// try date!!!!
require_once 'Date.php';
default:
- return sprintf($format,$this->col);
+ return sprintf($format, $this->col);
}
-
-
}
* @access public
* @return none
*/
- function debug($message, $logtype = 0, $level = 1)
+ public function debug($message, $logtype = 0, $level = 1)
{
global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
+ if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
(is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
return;
}
// this is a bit flaky due to php's wonderfull class passing around crap..
// but it's about as good as it gets..
- $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
+ $class = (isset($this) && is_a($this, 'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
if (!is_string($message)) {
- $message = print_r($message,true);
+ $message = print_r($message, true);
}
- if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
+ if (!is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && is_callable($_DB_DATAOBJECT['CONFIG']['debug'])) {
return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
}
return;
}
if (!is_string($message)) {
- $message = print_r($message,true);
+ $message = print_r($message, true);
}
$colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
* @access public
* @return none
*/
- static function debugLevel($v = null)
+ public static function debugLevel($v = null)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
* @access public
* @var object PEAR_Error (or false)
*/
- var $_lastError = false;
+ public $_lastError = false;
/**
* Default error handling is to create a pear error, but never return it.
* @access public
* @return error object
*/
- function raiseError($message, $type = null, $behaviour = null)
+ public function raiseError($message, $type = null, $behaviour = null)
{
global $_DB_DATAOBJECT;
$behaviour = null;
}
- $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
+ $error = &PEAR::getStaticProperty('DB_DataObject', 'lastError');
// no checks for production here?....... - we log errors before we throw them.
- DB_DataObject::debug($message,'ERROR',1);
+ DB_DataObject::debug($message, 'ERROR', 1);
if (PEAR::isError($message)) {
} else {
require_once 'DB/DataObject/Error.php';
$dor = new PEAR();
- $error = $dor->raiseError($message, $type, $behaviour,
- $opts=null, $userinfo=null, 'DB_DataObject_Error'
+ $error = $dor->raiseError(
+ $message,
+ $type,
+ $behaviour,
+ $opts=null,
+ $userinfo=null,
+ 'DB_DataObject_Error'
);
}
// this will never work totally with PHP's object model.
$_DB_DATAOBJECT['LASTERROR'] = $error;
- if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
+ if (isset($this) && is_object($this) && is_subclass_of($this, 'db_dataobject')) {
$this->_lastError = $error;
}
* @access public
* @return object an error object
*/
- function _loadConfig()
+ public function _loadConfig()
{
global $_DB_DATAOBJECT;
- $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
-
-
+ $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject', 'options');
}
- /**
- * Free global arrays associated with this object.
- *
- *
- * @access public
- * @return none
- */
- function free()
+ /**
+ * Free global arrays associated with this object.
+ *
+ *
+ * @access public
+ * @return none
+ */
+ public function free()
{
global $_DB_DATAOBJECT;
if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
}
- if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
+ if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
}
// clear the staticGet cache as well.
}
}
}
-
-
}
/**
* Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
- * If the value is a string set to "null" and the "disable_null_strings" option is not set to
+ * If the value is a string set to "null" and the "disable_null_strings" option is not set to
* true, then the value is considered to be null.
- * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to
+ * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to
* the value "full", then it will also be considered null. - this can not differenticate between not set
- *
- *
- * @param object|array $obj_or_ar
+ *
+ *
+ * @param object|array $obj_or_ar
* @param string|false $prop prperty
-
+
* @access private
* @return bool object
*/
- function _is_null($obj_or_ar , $prop)
+ public function _is_null($obj_or_ar, $prop)
{
- global $_DB_DATAOBJECT;
-
+ global $_DB_DATAOBJECT;
- $isset = $prop === false ? isset($obj_or_ar) :
+
+ $isset = $prop === false ? isset($obj_or_ar) :
(is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
- $value = $isset ?
- ($prop === false ? $obj_or_ar :
+ $value = $isset ?
+ ($prop === false ? $obj_or_ar :
(is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
: null;
- $options = $_DB_DATAOBJECT['CONFIG'];
-
+ $options = $_DB_DATAOBJECT['CONFIG'];
+
$null_strings = !isset($options['disable_null_strings'])
|| $options['disable_null_strings'] === false;
&& is_string($options['disable_null_strings'])
&& strtolower($options['disable_null_strings'] === 'full');
- if ( $null_strings && $isset && is_string($value) && (strtolower($value) === 'null') ) {
+ if ($null_strings && $isset && is_string($value) && (strtolower($value) === 'null')) {
return true;
}
- if ( $crazy_null && !$isset ) {
- return true;
+ if ($crazy_null && !$isset) {
+ return true;
}
return false;
-
-
}
/**
* (deprecated - use ::get / and your own caching method)
*/
- static function staticGet($class, $k, $v = null)
+ public static function staticGet($class, $k, $v = null)
{
$lclass = strtolower($class);
global $_DB_DATAOBJECT;
$key = $k;
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
+ DB_DataObject::debug("$class $key", "STATIC GET - TRY CACHE");
}
if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
}
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
+ DB_DataObject::debug("$class $key", "STATIC GET - NOT IN CACHE");
}
- $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
+ $obj = DB_DataObject::factory(substr($class, strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
if (PEAR::isError($obj)) {
$dor = new DB_DataObject();
$dor->raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
$_DB_DATAOBJECT['CACHE'][$lclass] = array();
}
- if (!$obj->get($k,$v)) {
+ if (!$obj->get($k, $v)) {
$dor = new DB_DataObject();
$dor->raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
* @access private
* @return string classname on Success
*/
- function staticAutoloadTable($table)
+ public function staticAutoloadTable($table)
{
global $_DB_DATAOBJECT;
if (empty($_DB_DATAOBJECT['CONFIG'])) {
}
$p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
$_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
- $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
+ $class = $p . preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table));
- $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
+ $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($class, false) : class_exists($class);
$class = $ce ? $class : DB_DataObject::_autoloadClass($class);
return $class;
}
/* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
- function _get_table() { return $this->table(); }
- function _get_keys() { return $this->keys(); }
-
-
-
-
+ public function _get_table()
+ {
+ return $this->table();
+ }
+ public function _get_keys()
+ {
+ return $this->keys();
+ }
}
// technially 4.3.2RC1 was broken!!
// looks like 4.3.3 may have problems too....
if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
-
- if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
- if (version_compare( phpversion(), "5") < 0) {
- overload('DB_DataObject');
- }
+ if ((phpversion() != '4.3.2-RC1') && (version_compare(phpversion(), "4.3.1") > 0)) {
+ if (version_compare(phpversion(), "5") < 0) {
+ overload('DB_DataObject');
+ }
$GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;
}
}
-
-
*/
/**
-*
+*
* Common usages:
* // blobs
* $data = DB_DataObject_Cast::blob($somefile);
* $d1 = new DB_DataObject_Cast::date('12/12/2000');
* $d2 = new DB_DataObject_Cast::date(2000,12,30);
* $d3 = new DB_DataObject_Cast::date($d1->year, $d1->month+30, $d1->day+30);
-*
+*
* // time, datetime.. ?????????
*
* // raw sql????
*
* // int's/string etc. are proably pretty pointless..!!!!
*
-*
-* inside DB_DataObject,
+*
+* inside DB_DataObject,
* if (is_a($v,'db_dataobject_class')) {
* $value .= $v->toString(DB_DATAOBJECT_INT,'mysql');
* }
*
*
-*/
-class DB_DataObject_Cast {
+*/
+class DB_DataObject_Cast
+{
/**
* Type of data Stored in the object..
*
* @var string (date|blob|.....?)
- * @access public
+ * @access public
*/
- var $type;
+ public $type;
/**
* Data For date representation
* @var int day/month/year
* @access public
*/
- var $day;
- var $month;
- var $year;
+ public $day;
+ public $month;
+ public $year;
/**
* @access public
*/
- var $value;
+ public $value;
* Blob consructor
*
* create a Cast object from some raw data.. (binary)
- *
- *
+ *
+ *
* @param string (with binary data!)
*
* @return object DB_DataObject_Cast
- * @access public
+ * @access public
*/
- function blob($value) {
+ public function blob($value)
+ {
$r = new DB_DataObject_Cast;
$r->type = 'blob';
$r->value = $value;
* String consructor (actually use if for ints and everything else!!!
*
* create a Cast object from some string (not binary)
- *
- *
+ *
+ *
* @param string (with binary data!)
*
* @return object DB_DataObject_Cast
- * @access public
+ * @access public
*/
- function string($value) {
+ public function string($value)
+ {
$r = new DB_DataObject_Cast;
$r->type = 'string';
$r->value = $value;
* SQL constructor (for raw SQL insert)
*
* create a Cast object from some sql
- *
+ *
* @param string (with binary data!)
*
* @return object DB_DataObject_Cast
- * @access public
+ * @access public
*/
- function sql($value)
+ public function sql($value)
{
$r = new DB_DataObject_Cast;
$r->type = 'sql';
*
* create a Cast object from some string (not binary)
* NO VALIDATION DONE, although some crappy re-calcing done!
- *
+ *
* @param vargs... accepts
* dd/mm
* dd/mm/yyyy
*
*
* @return object DB_DataObject_Cast
- * @access public
+ * @access public
*/
- function date()
- {
+ public function date()
+ {
$args = func_get_args();
- switch(count($args)) {
+ switch (count($args)) {
case 0: // no args = today!
- $bits = explode('-',date('Y-m-d'));
+ $bits = explode('-', date('Y-m-d'));
break;
- case 1: // one arg = a string
+ case 1: // one arg = a string
- if (strpos($args[0],'/') !== false) {
- $bits = array_reverse(explode('/',$args[0]));
+ if (strpos($args[0], '/') !== false) {
+ $bits = array_reverse(explode('/', $args[0]));
} else {
- $bits = explode('-',$args[0]);
+ $bits = explode('-', $args[0]);
}
break;
default: // 2 or more..
// fix me if anyone has more time...
if (($bits[0] < 1975) || ($bits[0] > 2030)) {
$oldyear = $bits[0];
- $bits = explode('-',date('Y-m-d',mktime(1,1,1,$bits[1],$bits[2],2000)));
+ $bits = explode('-', date('Y-m-d', mktime(1, 1, 1, $bits[1], $bits[2], 2000)));
$bits[0] = ($bits[0] - 2000) + $oldyear;
} else {
// now mktime
- $bits = explode('-',date('Y-m-d',mktime(1,1,1,$bits[1],$bits[2],$bits[0])));
+ $bits = explode('-', date('Y-m-d', mktime(1, 1, 1, $bits[1], $bits[2], $bits[0])));
}
$r = new DB_DataObject_Cast;
$r->type = 'date';
- list($r->year,$r->month,$r->day) = $bits;
+ list($r->year, $r->month, $r->day) = $bits;
return $r;
}
* @var int hour/minute/second
* @access public
*/
- var $hour;
- var $minute;
- var $second;
+ public $hour;
+ public $minute;
+ public $second;
/**
* create a Cast object from a Date/Time
* Maybe should accept a Date object.!
* NO VALIDATION DONE, although some crappy re-calcing done!
- *
+ *
* @param vargs... accepts
* noargs (now)
* yyyy-mm-dd HH:MM:SS (Iso)
- * array(yyyy,mm,dd,HH,MM,SS)
+ * array(yyyy,mm,dd,HH,MM,SS)
*
*
* @return object DB_DataObject_Cast
- * @access public
+ * @access public
* @author therion 5 at hotmail
*/
- function dateTime()
+ public function dateTime()
{
$args = func_get_args();
- switch(count($args)) {
+ switch (count($args)) {
case 0: // no args = now!
$datetime = date('Y-m-d G:i:s', mktime());
+ // no break
case 1:
// continue on from 0 args.
if (!isset($datetime)) {
// change the type!
$r->type = 'datetime';
- // should we mathematically sort this out..
+ // should we mathematically sort this out..
// (or just assume that no-one's dumb enough to enter 26:90:90 as a time!
$r->hour = $bits[3];
$r->minute = $bits[4];
$r->second = $bits[5];
return $r;
-
}
* @param vargs... accepts
* noargs (now)
* HH:MM:SS (Iso)
- * array(HH,MM,SS)
+ * array(HH,MM,SS)
*
*
* @return object DB_DataObject_Cast
- * @access public
+ * @access public
* @author therion 5 at hotmail
*/
- function time()
+ public function time()
{
$args = func_get_args();
switch (count($args)) {
case 0: // no args = now!
$time = date('G:i:s', mktime());
+ // no break
case 1:
// continue on from 0 args.
if (!isset($time)) {
$r->minute = $bits[1];
$r->second = $bits[2];
return $r;
-
}
/**
* get the string to use in the SQL statement for this...
*
- *
+ *
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
*/
- function toString($to=false,$db)
+ public function toString($to=false, $db)
{
// if $this->type is not set, we are in serious trouble!!!!
// values for to:
$method = 'toStringFrom'.$this->type;
- return $this->$method($to,$db);
+ return $this->$method($to, $db);
}
/**
- * get the string to use in the SQL statement from a blob of binary data
+ * get the string to use in the SQL statement from a blob of binary data
* ** Suppots only blob->postgres::bytea
*
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
*/
- function toStringFromBlob($to,$db)
+ public function toStringFromBlob($to, $db)
{
// first weed out invalid casts..
// in blobs can only be cast to blobs.!
return "'".pg_escape_bytea($this->value)."'::bytea";
case 'mysql':
- return "'".mysql_real_escape_string($this->value,$db->connection)."'";
+ return "'".mysql_real_escape_string($this->value, $db->connection)."'";
case 'mysqli':
// this is funny - the parameter order is reversed ;)
case 'mssql':
- if(is_numeric($this->value)) {
+ if (is_numeric($this->value)) {
return $this->value;
}
$unpacked = unpack('H*hex', $this->value);
default:
return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:{$db->dsn['phptype']} Yet");
}
-
}
/**
* get the string to use in the SQL statement for a blob from a string!
* ** Suppots only string->postgres::bytea
- *
+ *
*
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
*/
- function toStringFromString($to,$db)
+ public function toStringFromString($to, $db)
{
// first weed out invalid casts..
// in blobs can only be cast to blobs.!
// perhaps we should support TEXT fields???
- //
+ //
// $to == a string field which is the default type (0)
// so we do not test it here. - we assume that number fields
// will accept a string?? - which is stretching it a bit ...
- // should probaly add that test as some point.
+ // should probaly add that test as some point.
switch ($db->dsn['phptype']) {
case 'pgsql':
return "'".pg_escape_string($this->value)."'::bytea";
case 'mysql':
- return "'".mysql_real_escape_string($this->value,$db->connection)."'";
+ return "'".mysql_real_escape_string($this->value, $db->connection)."'";
case 'mysqli':
case 'mssql':
// copied from the old DB mssql code...?? not sure how safe this is.
return "'" . str_replace(
- array("'", "\\\r\n", "\\\n"),
- array("''", "\\\\\r\n\r\n", "\\\\\n\n"),
- $this->value
+ array("'", "\\\r\n", "\\\n"),
+ array("''", "\\\\\r\n\r\n", "\\\\\n\n"),
+ $this->value
) . "'";
default:
return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:{$db->dsn['phptype']} Yet");
}
-
}
/**
* get the string to use in the SQL statement for a date
- *
- *
+ *
+ *
*
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
*/
- function toStringFromDate($to,$db)
+ public function toStringFromDate($to, $db)
{
// first weed out invalid casts..
// in blobs can only be cast to blobs.!
- // perhaps we should support TEXT fields???
- //
+ // perhaps we should support TEXT fields???
+ //
if (($to !== false) && !($to & DB_DATAOBJECT_DATE)) {
return PEAR::raiseError('Invalid Cast from a DB_DataObject_Cast::string to something other than a date!'.
/**
* get the string to use in the SQL statement for a datetime
- *
- *
+ *
+ *
*
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
* @author therion 5 at hotmail
*/
- function toStringFromDateTime($to,$db)
+ public function toStringFromDateTime($to, $db)
{
// first weed out invalid casts..
// in blobs can only be cast to blobs.!
// perhaps we should support TEXT fields???
- if (($to !== false) &&
+ if (($to !== false) &&
!($to & (DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME))) {
return PEAR::raiseError('Invalid Cast from a ' .
' DB_DataObject_Cast::dateTime to something other than a datetime!' .
/**
* get the string to use in the SQL statement for a time
- *
- *
+ *
+ *
*
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
* @author therion 5 at hotmail
*/
- function toStringFromTime($to,$db)
+ public function toStringFromTime($to, $db)
{
// first weed out invalid casts..
// in blobs can only be cast to blobs.!
// perhaps we should support TEXT fields???
if (($to !== false) && !($to & DB_DATAOBJECT_TIME)) {
- return PEAR::raiseError('Invalid Cast from a' .
+ return PEAR::raiseError('Invalid Cast from a' .
' DB_DataObject_Cast::time to something other than a time!'.
' (try using native features)');
}
*
* @param int $to Type (DB_DATAOBJECT_*
* @param object $db DB Connection Object
- *
*
- * @return string
+ *
+ * @return string
* @access public
*/
- function toStringFromSql($to,$db)
+ public function toStringFromSql($to, $db)
{
- return $this->value;
+ return $this->value;
}
-
-
-
}
-
*
* @see PEAR_Error
*/
- function DB_DataObject_Error($message = '', $code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE)
- {
+ public function DB_DataObject_Error(
+ $message = '',
+ $code = DB_ERROR,
+ $mode = PEAR_ERROR_RETURN,
+ $level = E_USER_NOTICE
+ ) {
$this->PEAR_Error('DB_DataObject Error: ' . $message, $code, $mode, $level);
-
}
// todo : - support code -> message handling, and translated error messages...
-
-
-
}
* class definitions, we now check for quotes and semi-colon's in both variables
* so I cant see how it would be possible to generate code even if
* for some crazy reason you took the classname and table name from User Input.
- *
+ *
* If you consider that wrong, or can prove it.. let me know!
*/
/**
- *
+ *
* Config _$ptions
* [DB_DataObject]
* ; optional default = DB/DataObject.php
* @var array
* @access private
*/
- var $tables;
+ public $tables;
/**
* associative array table -> array of table row objects
* @var array
* @access private
*/
- var $_definitions;
+ public $_definitions;
/**
* active table being output
* @var string
* @access private
*/
- var $table; // active tablename
+ public $table; // active tablename
/**
* links (generated)
* @var array
* @access private
*/
- var $_fkeys; // active tablename
+ public $_fkeys; // active tablename
/**
* The 'starter' = call this to start the process
* @access public
* @return none
*/
- function start()
+ public function start()
{
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
$databases = array();
- foreach($options as $k=>$v) {
- if (substr($k,0,9) == 'database_') {
- $databases[substr($k,9)] = $v;
+ foreach ($options as $k=>$v) {
+ if (substr($k, 0, 9) == 'database_') {
+ $databases[substr($k, 9)] = $v;
}
}
}
}
- foreach($databases as $databasename => $database) {
+ foreach ($databases as $databasename => $database) {
if (!$database) {
continue;
}
$t->_createTableList();
$t->_createForiegnKeys();
- foreach(get_class_methods($class) as $method) {
- if (substr($method,0,8 ) != 'generate') {
+ foreach (get_class_methods($class) as $method) {
+ if (substr($method, 0, 8) != 'generate') {
continue;
}
$this->debug("calling $method");
* @var string outputbuffer for table definitions
* @access private
*/
- var $_newConfig;
+ public $_newConfig;
/**
* Build a list of tables;
* @access private
* @return none
*/
- function _createTableList()
+ public function _createTableList()
{
$this->_connect();
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
$is_MDB2 = ($db_driver != 'DB') ? true : false;
- if (is_object($__DB) && is_a($__DB , 'PEAR_Error')) {
+ if (is_object($__DB) && is_a($__DB, 'PEAR_Error')) {
return PEAR::raiseError($__DB->toString(), null, PEAR_ERROR_DIE);
}
/**
* set portability and some modules to fetch the informations
*/
- $db_options = PEAR::getStaticProperty('MDB2','options');
+ $db_options = PEAR::getStaticProperty('MDB2', 'options');
if (empty($db_options)) {
$__DB->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE);
}
$__DB->loadModule('Reverse');
}
- if ((empty($this->tables) || (is_object($this->tables) && is_a($this->tables , 'PEAR_Error')))) {
+ if ((empty($this->tables) || (is_object($this->tables) && is_a($this->tables, 'PEAR_Error')))) {
//if that fails fall back to clasic tables list.
if (!$is_MDB2) {
// try getting a list of schema tables first. (postgres)
$__DB->expectError(DB_ERROR_UNSUPPORTED);
$this->tables = $__DB->getListOf('tables');
$__DB->popExpect();
- } else {
+ } else {
$this->tables = $__DB->manager->listTables();
$sequences = $__DB->manager->listSequences();
foreach ($sequences as $k => $v) {
}
}
- if (is_object($this->tables) && is_a($this->tables , 'PEAR_Error')) {
+ if (is_object($this->tables) && is_a($this->tables, 'PEAR_Error')) {
return PEAR::raiseError($this->tables->toString(), null, PEAR_ERROR_DIE);
}
} else {
$views = $__DB->manager->listViews();
}
- if (is_object($views) && is_a($views,'PEAR_Error')) {
+ if (is_object($views) && is_a($views, 'PEAR_Error')) {
return PEAR::raiseError(
- 'Error getting Views (check the PEAR bug database for the fix to DB), ' .
+ 'Error getting Views (check the PEAR bug database for the fix to DB), ' .
$views->toString(),
- null,
- PEAR_ERROR_DIE
+ null,
+ PEAR_ERROR_DIE
);
}
- $this->tables = array_merge ($this->tables, $views);
+ $this->tables = array_merge($this->tables, $views);
}
// declare a temporary table to be filled with matching tables names
$tmp_table = array();
- foreach($this->tables as $table) {
+ foreach ($this->tables as $table) {
if (isset($options['generator_include_regex']) &&
- !preg_match($options['generator_include_regex'],$table)) {
+ !preg_match($options['generator_include_regex'], $table)) {
$this->debug("SKIPPING (generator_include_regex) : $table");
continue;
- }
+ }
if (isset($options['generator_exclude_regex']) &&
- preg_match($options['generator_exclude_regex'],$table)) {
+ preg_match($options['generator_exclude_regex'], $table)) {
continue;
}
$strip = (is_string($strip) && strtolower($strip) == 'true') ? true : $strip;
// postgres strip the schema bit from the
- if (!empty($strip) ) {
-
- if (!is_string($strip) || preg_match($strip, $table)) {
- $bits = explode('.', $table,2);
+ if (!empty($strip)) {
+ if (!is_string($strip) || preg_match($strip, $table)) {
+ $bits = explode('.', $table, 2);
$table = $bits[0];
if (count($bits) > 1) {
$table = $bits[1];
}
$this->debug("EXTRACTING : $table");
- $quotedTable = !empty($options['quote_identifiers_tableinfo']) ?
+ $quotedTable = !empty($options['quote_identifiers_tableinfo']) ?
$__DB->quoteIdentifier($table) : $table;
if (!$is_MDB2) {
-
$defs = $__DB->tableInfo($quotedTable);
} else {
$defs = $__DB->reverse->tableInfo($quotedTable);
// rename the length value, so it matches db's return.
-
}
- if (is_object($defs) && is_a($defs,'PEAR_Error')) {
+ if (is_object($defs) && is_a($defs, 'PEAR_Error')) {
// running in debug mode should pick this up as a big warning..
$this->debug("Error reading tableInfo: $table");
$this->raiseError('Error reading tableInfo, '. $defs->toString());
- foreach($defs as $def) {
+ foreach ($defs as $def) {
if (!is_array($def)) {
continue;
}
$def['len'] = $def['length'];
}
$this->_definitions[$table][] = (object) $def;
-
}
// we find a matching table, just store it into a temporary array
$tmp_table[] = $table;
-
-
}
// the temporary table array is now the right one (tables names matching
// with regex expressions have been removed)
* @access private
* @return none
*/
- function generateDefinitions()
+ public function generateDefinitions()
{
$this->debug("Generating Definitions file: ");
if (!$this->tables) {
return;
}
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
//$this->_newConfig = new Config('IniFile');
$this->_newConfig = '';
- foreach($this->tables as $this->table) {
+ foreach ($this->tables as $this->table) {
$this->_generateDefinitionsTable();
}
$this->_connect();
// dont generate a schema if location is not set
// it's created on the fly!
- if (empty($options['schema_location']) && empty($options["ini_{$this->_database}"]) ) {
+ if (empty($options['schema_location']) && empty($options["ini_{$this->_database}"])) {
return;
}
if (!empty($options['generator_no_ini'])) { // built in ini files..
}
$this->debug("Writing ini as {$file}\n");
//touch($file);
- $tmpname = tempnam(session_save_path(),'DataObject_');
+ $tmpname = tempnam(session_save_path(), 'DataObject_');
//print_r($this->_newConfig);
- $fh = fopen($tmpname,'w');
+ $fh = fopen($tmpname, 'w');
if (!$fh) {
return PEAR::raiseError(
"Failed to create temporary file: $tmpname\n".
- "make sure session.save_path is set and is writable\n"
- ,null, PEAR_ERROR_DIE);
+ "make sure session.save_path is set and is writable\n",
+ null,
+ PEAR_ERROR_DIE
+ );
}
- fwrite($fh,$this->_newConfig);
+ fwrite($fh, $this->_newConfig);
fclose($fh);
$perms = file_exists($file) ? fileperms($file) : 0755;
// windows can fail doing this. - not a perfect solution but otherwise it's getting really kludgy..
- if (!@rename($tmpname, $file)) {
- unlink($file);
+ if (!@rename($tmpname, $file)) {
+ unlink($file);
rename($tmpname, $file);
}
- chmod($file,$perms);
+ chmod($file, $perms);
//$ret = $this->_newConfig->writeInput($file,false);
//if (PEAR::isError($ret) ) {
// return PEAR::raiseError($ret->message,null,PEAR_ERROR_DIE);
// }
}
- /**
- * create the data for Foreign Keys (for links.ini)
- * Currenly only works with mysql / mysqli / posgtreas
- * to use, you must set option: generate_links=true
- *
- * @author Pascal Sch�ni
- */
+ /**
+ * create the data for Foreign Keys (for links.ini)
+ * Currenly only works with mysql / mysqli / posgtreas
+ * to use, you must set option: generate_links=true
+ *
+ * @author Pascal Sch�ni
+ */
- function _createForiegnKeys()
+ public function _createForiegnKeys()
{
- $options = PEAR::getStaticProperty('DB_DataObject','options');
+ $options = PEAR::getStaticProperty('DB_DataObject', 'options');
if (empty($options['generate_links'])) {
return false;
}
case 'pgsql':
- foreach($this->tables as $this->table) {
+ foreach ($this->tables as $this->table) {
$quotedTable = !empty($options['quote_identifiers_tableinfo']) ? $DB->quoteIdentifier($table) : $this->table;
$res =& $DB->query("SELECT
pg_catalog.pg_get_constraintdef(r.oid, true) AS condef
preg_match(
"/FOREIGN KEY \((\w*)\) REFERENCES (\w*)\((\w*)\)/i",
$row['condef'],
- $treffer);
+ $treffer
+ );
if (!count($treffer)) {
continue;
}
case 'mysql':
case 'mysqli':
- default:
+ default:
- foreach($this->tables as $this->table) {
+ foreach ($this->tables as $this->table) {
$quotedTable = !empty($options['quote_identifiers_tableinfo']) ? $DB->quoteIdentifier($table) : $this->table;
- $res =& $DB->query('SHOW CREATE TABLE ' . $quotedTable );
+ $res =& $DB->query('SHOW CREATE TABLE ' . $quotedTable);
if (PEAR::isError($res)) {
die($res->getMessage());
$treffer = array();
// Extract FOREIGN KEYS
preg_match_all(
- "/FOREIGN KEY \(`(\w*)`\) REFERENCES `(\w*)` \(`(\w*)`\)/i",
- $text[1],
- $treffer,
- PREG_SET_ORDER);
+ "/FOREIGN KEY \(`(\w*)`\) REFERENCES `(\w*)` \(`(\w*)`\)/i",
+ $text[1],
+ $treffer,
+ PREG_SET_ORDER
+ );
if (!count($treffer)) {
continue;
}
- foreach($treffer as $i=> $tref) {
+ foreach ($treffer as $i=> $tref) {
$fk[$this->table][$tref[1]] = $tref[2] . ":" . $tref[3];
}
-
}
}
$this->_fkeys = $fk;
-
-
-
-
-
}
/**
- * generate Foreign Keys (for links.ini)
+ * generate Foreign Keys (for links.ini)
* Currenly only works with mysql / mysqli
* to use, you must set option: generate_links=true
- *
- * @author Pascal Sch�ni
+ *
+ * @author Pascal Sch�ni
*/
- function generateForeignKeys()
+ public function generateForeignKeys()
{
- $options = PEAR::getStaticProperty('DB_DataObject','options');
+ $options = PEAR::getStaticProperty('DB_DataObject', 'options');
if (empty($options['generate_links'])) {
return false;
}
$fk = $this->_fkeys;
$links_ini = "";
- foreach($fk as $table => $details) {
+ foreach ($fk as $table => $details) {
$links_ini .= "[$table]\n";
foreach ($details as $col => $ref) {
$links_ini .= "$col = $ref\n";
// dont generate a schema if location is not set
// it's created on the fly!
- $options = PEAR::getStaticProperty('DB_DataObject','options');
+ $options = PEAR::getStaticProperty('DB_DataObject', 'options');
if (!empty($options['schema_location'])) {
- $file = "{$options['schema_location']}/{$this->_database}.links.ini";
+ $file = "{$options['schema_location']}/{$this->_database}.links.ini";
} elseif (isset($options["ini_{$this->_database}"])) {
- $file = preg_replace('/\.ini/','.links.ini',$options["ini_{$this->_database}"]);
+ $file = preg_replace('/\.ini/', '.links.ini', $options["ini_{$this->_database}"]);
} else {
$this->debug("generateForeignKeys: SKIP - schema_location or ini_{database} was not set");
return;
if (!file_exists(dirname($file))) {
- mkdir(dirname($file),0755, true);
+ mkdir(dirname($file), 0755, true);
}
$this->debug("Writing ini as {$file}\n");
//touch($file); // not sure why this is needed?
- $tmpname = tempnam(session_save_path(),'DataObject_');
+ $tmpname = tempnam(session_save_path(), 'DataObject_');
- $fh = fopen($tmpname,'w');
+ $fh = fopen($tmpname, 'w');
if (!$fh) {
return PEAR::raiseError(
"Failed to create temporary file: $tmpname\n".
- "make sure session.save_path is set and is writable\n"
- ,null, PEAR_ERROR_DIE);
+ "make sure session.save_path is set and is writable\n",
+ null,
+ PEAR_ERROR_DIE
+ );
}
- fwrite($fh,$links_ini);
+ fwrite($fh, $links_ini);
fclose($fh);
$perms = file_exists($file) ? fileperms($file) : 0755;
// windows can fail doing this. - not a perfect solution but otherwise it's getting really kludgy..
- if (!@rename($tmpname, $file)) {
- unlink($file);
+ if (!@rename($tmpname, $file)) {
+ unlink($file);
rename($tmpname, $file);
}
chmod($file, $perms);
* @access private
* @return tabledef and keys array.
*/
- function _generateDefinitionsTable()
+ public function _generateDefinitionsTable()
{
global $_DB_DATAOBJECT;
- $options = PEAR::getStaticProperty('DB_DataObject','options');
+ $options = PEAR::getStaticProperty('DB_DataObject', 'options');
$defs = $this->_definitions[$this->table];
$this->_newConfig .= "\n[{$this->table}]\n";
$keys_out = "\n[{$this->table}__keys]\n";
- foreach($defs as $t) {
-
+ foreach ($defs as $t) {
$n=0;
$write_ini = true;
case 'DECIMAL':
case 'MONEY': // mssql and maybe others
case 'NUMERIC':
- case 'NUMBER': // oci8
+ case 'NUMBER': // oci8
$type = DB_DATAOBJECT_INT; // should really by FLOAT!!! / MONEY...
break;
case 'YEAR':
- $type = DB_DATAOBJECT_INT;
+ $type = DB_DATAOBJECT_INT;
break;
case 'BIT':
- case 'BOOL':
- case 'BOOLEAN':
+ case 'BOOL':
+ case 'BOOLEAN':
$type = DB_DATAOBJECT_BOOL;
// postgres needs to quote '0'
break;
- case 'DATE':
+ case 'DATE':
$type = DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE;
break;
- case 'TIME':
+ case 'TIME':
$type = DB_DATAOBJECT_STR + DB_DATAOBJECT_TIME;
- break;
+ break;
- case 'DATETIME':
+ case 'DATETIME':
$type = DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME;
- break;
+ break;
case 'TIMESTAMP': // do other databases use this???
$type = ($dbtype == 'mysql') ?
- DB_DATAOBJECT_MYSQLTIMESTAMP :
+ DB_DATAOBJECT_MYSQLTIMESTAMP :
DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME;
- break;
+ break;
case 'BLOB': /// these should really be ignored!!!???
$type = DB_DATAOBJECT_STR + DB_DATAOBJECT_BLOB;
break;
- default:
+ default:
echo "*****************************************************************\n".
"** WARNING UNKNOWN TYPE **\n".
"** Found column '{$t->name}', of type '{$t->type}' **\n".
continue; // is this a bug?
}
- if (preg_match('/not[ _]null/i',$t->flags)) {
+ if (preg_match('/not[ _]null/i', $t->flags)) {
$type += DB_DATAOBJECT_NOTNULL;
}
- if (in_array($t->name,array('null','yes','no','true','false'))) {
+ if (in_array($t->name, array('null','yes','no','true','false'))) {
echo "*****************************************************************\n".
"** WARNING **\n".
"** Found column '{$t->name}', which is invalid in an .ini file **\n".
$secondary_key_match = isset($options['generator_secondary_key_match']) ? $options['generator_secondary_key_match'] : 'primary|unique';
$m = array();
- if (preg_match('/(auto_increment|nextval\(([^)]*))/i',rawurldecode($t->flags),$m)
+ if (preg_match('/(auto_increment|nextval\(([^)]*))/i', rawurldecode($t->flags), $m)
|| (isset($t->autoincrement) && ($t->autoincrement === true))) {
-
$sn = 'N';
- if ($DB->phptype == 'pgsql' && !empty($m[2])) {
- $sn = preg_replace('/[("]+/','', $m[2]);
+ if ($DB->phptype == 'pgsql' && !empty($m[2])) {
+ $sn = preg_replace('/[("]+/', '', $m[2]);
//echo urldecode($t->flags) . "\n" ;
}
// native sequences = 2
$keys_out_primary .= "{$t->name} = $sn\n";
}
$ret_keys_primary[$t->name] = $sn;
-
- } else if ($secondary_key_match && preg_match('/('.$secondary_key_match.')/i',$t->flags)) {
+ } elseif ($secondary_key_match && preg_match('/('.$secondary_key_match.')/i', $t->flags)) {
// keys.. = 1
$key_type = 'K';
- if (!preg_match("/(primary)/i",$t->flags)) {
+ if (!preg_match("/(primary)/i", $t->flags)) {
$key_type = 'U';
}
}
$ret_keys_secondary[$t->name] = $key_type;
}
-
-
}
$this->_newConfig .= $keys_out . (empty($keys_out_primary) ? $keys_out_secondary : $keys_out_primary);
}
return $ret;
-
-
}
/**
*/
- function getClassNameFromTableName($table)
+ public function getClassNameFromTableName($table)
{
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$class_prefix = empty($options['class_prefix']) ? '' : $options['class_prefix'];
- return $class_prefix.preg_replace('/[^A-Z0-9]/i','_',ucfirst(trim($this->table)));
+ return $class_prefix.preg_replace('/[^A-Z0-9]/i', '_', ucfirst(trim($this->table)));
}
*/
- function getFileNameFromTableName($table)
+ public function getFileNameFromTableName($table)
{
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$base = $options['class_location'];
- if (strpos($base,'%s') !== false) {
+ if (strpos($base, '%s') !== false) {
$base = dirname($base);
- }
+ }
if (!file_exists($base)) {
require_once 'System.php';
System::mkdir(array('-p',$base));
}
- if (strpos($options['class_location'],'%s') !== false) {
- $outfilename = sprintf($options['class_location'],
- preg_replace('/[^A-Z0-9]/i','_',ucfirst($this->table)));
- } else {
- $outfilename = "{$base}/".preg_replace('/[^A-Z0-9]/i','_',ucfirst($this->table)).".php";
+ if (strpos($options['class_location'], '%s') !== false) {
+ $outfilename = sprintf(
+ $options['class_location'],
+ preg_replace('/[^A-Z0-9]/i', '_', ucfirst($this->table))
+ );
+ } else {
+ $outfilename = "{$base}/".preg_replace('/[^A-Z0-9]/i', '_', ucfirst($this->table)).".php";
}
return $outfilename;
-
}
- /**
+ /**
* Convert a column name into a method name (usually prefixed by get/set/validateXXXXX)
*
* @access public
*/
- function getMethodNameFromColumnName($col)
+ public function getMethodNameFromColumnName($col)
{
return ucfirst($col);
}
* building the class files
* for each of the tables output a file!
*/
- function generateClasses()
+ public function generateClasses()
{
//echo "Generating Class files: \n";
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$this->_extends = empty($options['extends']) ? $this->_extends : $options['extends'];
$this->_extendsFile = !isset($options['extends_location']) ? $this->_extendsFile : $options['extends_location'];
- foreach($this->tables as $this->table) {
+ foreach ($this->tables as $this->table) {
$this->table = trim($this->table);
$this->classname = $this->getClassNameFromTableName($this->table);
$i = '';
$oldcontents = '';
if (file_exists($outfilename)) {
// file_get_contents???
- $oldcontents = implode('',file($outfilename));
+ $oldcontents = implode('', file($outfilename));
}
$out = $this->_generateClassTable($oldcontents);
- $this->debug( "writing $this->classname\n");
- $tmpname = tempnam(session_save_path(),'DataObject_');
+ $this->debug("writing $this->classname\n");
+ $tmpname = tempnam(session_save_path(), 'DataObject_');
$fh = fopen($tmpname, "w");
if (!$fh) {
return PEAR::raiseError(
"Failed to create temporary file: $tmpname\n".
- "make sure session.save_path is set and is writable\n"
- ,null, PEAR_ERROR_DIE);
+ "make sure session.save_path is set and is writable\n",
+ null,
+ PEAR_ERROR_DIE
+ );
}
- fputs($fh,$out);
+ fputs($fh, $out);
fclose($fh);
$perms = file_exists($outfilename) ? fileperms($outfilename) : 0755;
// windows can fail doing this. - not a perfect solution but otherwise it's getting really kludgy..
if (!@rename($tmpname, $outfilename)) {
- unlink($outfilename);
+ unlink($outfilename);
rename($tmpname, $outfilename);
}
* @var string
* @access private
*/
- var $_extends = 'DB_DataObject';
+ public $_extends = 'DB_DataObject';
/**
* line to use for require('DB/DataObject.php');
* @var string
* @access private
*/
- var $_extendsFile = "DB/DataObject.php";
+ public $_extendsFile = "DB/DataObject.php";
/**
* class being generated
* @var string
* @access private
*/
- var $_className;
+ public $_className;
/**
* The table class geneation part - single file.
* @access private
* @return none
*/
- function _generateClassTable($input = '')
+ public function _generateClassTable($input = '')
{
// title = expand me!
$foot = "";
$head .= "require_once '{$this->_extendsFile}';\n\n";
}
// add dummy class header in...
- // class
+ // class
$head .= $this->derivedHookClassDocBlock();
$head .= "class {$this->classname} extends {$this->_extends} \n{";
$body .= " /* the code below is auto generated do not remove the above tag */\n\n";
// table
- $p = str_repeat(' ',max(2, (18 - strlen($this->table)))) ;
+ $p = str_repeat(' ', max(2, (18 - strlen($this->table)))) ;
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
- $var = (substr(phpversion(),0,1) > 4) ? 'public' : 'var';
+ $var = (substr(phpversion(), 0, 1) > 4) ? 'public' : 'var';
$var = !empty($options['generator_var_keyword']) ? $options['generator_var_keyword'] : $var;
// if we are using the option database_{databasename} = dsn
// then we should add var $_database = here
- // as database names may not always match..
+ // 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
+ // Only include the $_database property if the omit_database_var is unset or false
if (isset($options["database_{$this->_database}"]) && empty($GLOBALS['_DB_DATAOBJECT']['CONFIG']['generator_omit_database_var'])) {
- $p = str_repeat(' ', max(2, (16 - strlen($this->_database))));
+ $p = str_repeat(' ', max(2, (16 - strlen($this->_database))));
$body .= " {$var} \$_database = '{$this->_database}'; {$p}// database name (used with database_{*} config)\n";
}
$connections = array();
$sets = array();
- foreach($defs as $t) {
+ foreach ($defs as $t) {
if (!strlen(trim($t->name))) {
continue;
}
continue;
}
- $pad = str_repeat(' ',max(2, (30 - strlen($t->name))));
+ $pad = str_repeat(' ', max(2, (30 - strlen($t->name))));
$length = empty($t->len) ? '' : '('.$t->len.')';
$flags = strlen($t->flags) ? (' '. trim($t->flags)) : '';
// 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);
- $body .= $this->derivedHookVar($t,strlen($p));
+ $body .= $this->derivedHookVar($t, strlen($p));
}
$body .= $this->derivedHookPostVar($defs);
// and replace them with $x = clone($y);
// due to the change in the PHP5 clone design.
$static = 'static';
- if ( substr(phpversion(),0,1) < 5) {
+ if (substr(phpversion(), 0, 1) < 5) {
$body .= "\n";
$body .= " /* ZE2 compatibility trick*/\n";
$body .= " function __clone() { return \$this;}\n";
$body .= $this->_generateKeysFunction($def['keys']);
$body .= $this->_generateSequenceKeyFunction($def);
$body .= $this->_generateDefaultsFunction($this->table, $def['table']);
- } else if (!empty($options['generator_add_defaults'])) {
+ } elseif (!empty($options['generator_add_defaults'])) {
// I dont really like doing it this way (adding another option)
// but it helps on older projects.
$def = $this->_generateDefinitionsTable(); // simplify this!?
- $body .= $this->_generateDefaultsFunction($this->table,$def['table']);
-
+ $body .= $this->_generateDefaultsFunction($this->table, $def['table']);
}
$body .= $this->derivedHookFunctions($input);
// stubs..
if (!empty($options['generator_add_validate_stubs'])) {
- foreach($defs as $t) {
+ foreach ($defs as $t) {
if (!strlen(trim($t->name))) {
continue;
}
if (!$input) {
return $full;
}
- if (!preg_match('/(\n|\r\n)\s*###START_AUTOCODE(\n|\r\n)/s',$input)) {
+ if (!preg_match('/(\n|\r\n)\s*###START_AUTOCODE(\n|\r\n)/s', $input)) {
return $full;
}
- if (!preg_match('/(\n|\r\n)\s*###END_AUTOCODE(\n|\r\n)/s',$input)) {
+ if (!preg_match('/(\n|\r\n)\s*###END_AUTOCODE(\n|\r\n)/s', $input)) {
return $full;
}
unless use set generator_class_rewrite to ANY or a name*/
$class_rewrite = 'DB_DataObject';
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
if (empty($options['generator_class_rewrite']) || !($class_rewrite = $options['generator_class_rewrite'])) {
$class_rewrite = 'DB_DataObject';
}
$input = preg_replace(
'/(\n|\r\n)class\s*[a-z0-9_]+\s*extends\s*' .$class_rewrite . '\s*(\n|\r\n)\{(\n|\r\n)/si',
"\nclass {$this->classname} extends {$this->_extends} \n{\n",
- $input);
+ $input
+ );
$ret = preg_replace(
'/(\n|\r\n)\s*###START_AUTOCODE(\n|\r\n).*(\n|\r\n)\s*###END_AUTOCODE(\n|\r\n)/s',
- $body,$input);
+ $body,
+ $input
+ );
if (!strlen($ret)) {
return PEAR::raiseError(
"PREG_REPLACE failed to replace body, - you probably need to set these in your php.ini\n".
"pcre.backtrack_limit=1000000\n".
- "pcre.recursion_limit=1000000\n"
- ,null, PEAR_ERROR_DIE);
- }
+ "pcre.recursion_limit=1000000\n",
+ null,
+ PEAR_ERROR_DIE
+ );
+ }
return $ret;
}
* @access public
* @return string added to class eg. functions.
*/
- function derivedHookFunctions($input = "")
+ public function derivedHookFunctions($input = "")
{
// This is so derived generator classes can generate functions
// It MUST NOT be changed here!!!
* @access public
* @return string added to class eg. functions.
*/
- function derivedHookVar(&$t,$padding)
+ public function derivedHookVar(&$t, $padding)
{
// This is so derived generator classes can generate variabels
// It MUST NOT be changed here!!!
* @access public
* @return string added to class eg. functions.
*/
- function derivedHookPostVar($t)
+ public function derivedHookPostVar($t)
{
// This is so derived generator classes can generate variabels
// It MUST NOT be changed here!!!
* @access public
* @return string added to class eg. functions.
*/
- function derivedHookPageLevelDocBlock() {
+ public function derivedHookPageLevelDocBlock()
+ {
return '';
}
* @access public
* @return string added to class eg. functions.
*/
- function derivedHookExtendsDocBlock() {
+ public function derivedHookExtendsDocBlock()
+ {
return '';
}
* @access public
* @return string added to class eg. functions.
*/
- function derivedHookClassDocBlock() {
+ public function derivedHookClassDocBlock()
+ {
return '';
}
* getProxyFull - create a class definition on the fly and instantate it..
*
* similar to generated files - but also evals the class definitoin code.
- *
- *
+ *
+ *
* @param string database name
* @param string table name of table to create proxy for.
- *
+ *
*
* @return object Instance of class. or PEAR Error
* @access public
*/
- function getProxyFull($database,$table)
+ public function getProxyFull($database, $table)
{
-
- if ($err = $this->fillTableSchema($database,$table)) {
+ if ($err = $this->fillTableSchema($database, $table)) {
return $err;
}
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$class_prefix = empty($options['class_prefix']) ? '' : $options['class_prefix'];
$this->_extends = empty($options['extends']) ? $this->_extends : $options['extends'];
//echo $out;
eval('?>'.$out);
return new $classname;
-
}
- /**
+ /**
* fillTableSchema - set the database schema on the fly
*
- *
- *
+ *
+ *
* @param string database name
* @param string table name of table to create schema info for
*
* @return none | PEAR::error()
* @access public
*/
- function fillTableSchema($database,$table)
+ public function fillTableSchema($database, $table)
{
global $_DB_DATAOBJECT;
- // a little bit of sanity testing.
- if ((false !== strpos($database,"'")) || (false !== strpos($database,";"))) {
+ // a little bit of sanity testing.
+ if ((false !== strpos($database, "'")) || (false !== strpos($database, ";"))) {
return PEAR::raiseError("Error: Database name contains a quote or semi-colon", null, PEAR_ERROR_DIE);
}
- $this->_database = $database;
+ $this->_database = $database;
$this->_connect();
$table = trim($table);
// a little bit of sanity testing.
- if ((false !== strpos($table,"'")) || (false !== strpos($table,";"))) {
+ if ((false !== strpos($table, "'")) || (false !== strpos($table, ";"))) {
return PEAR::raiseError("Error: Table contains a quote or semi-colon", null, PEAR_ERROR_DIE);
}
$__DB= &$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
- $options = PEAR::getStaticProperty('DB_DataObject','options');
+ $options = PEAR::getStaticProperty('DB_DataObject', 'options');
$db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
$is_MDB2 = ($db_driver != 'DB') ? true : false;
$__DB->loadModule('Manager');
$__DB->loadModule('Reverse');
}
- $quotedTable = !empty($options['quote_identifiers_tableinfo']) ?
+ $quotedTable = !empty($options['quote_identifiers_tableinfo']) ?
$__DB->quoteIdentifier($table) : $table;
if (!$is_MDB2) {
if (PEAR::isError($defs)) {
return $defs;
- }
+ }
if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 2) {
- $this->debug("getting def for $database/$table",'fillTable');
- $this->debug(print_r($defs,true),'defs');
+ $this->debug("getting def for $database/$table", 'fillTable');
+ $this->debug(print_r($defs, true), 'defs');
}
// cast all definitions to objects - as we deal with that better.
- foreach($defs as $def) {
+ foreach ($defs as $def) {
if (is_array($def)) {
$this->_definitions[$table][] = (object) $def;
}
$_DB_DATAOBJECT['INI'][$database][$table] = $ret['table'];
$_DB_DATAOBJECT['INI'][$database][$table.'__keys'] = $ret['keys'];
return false;
-
}
/**
* @return string
* @access public
*/
- function _generateGetters($input)
+ public function _generateGetters($input)
{
-
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$getters = '';
// only generate if option is set to true
- if (empty($options['generate_getters'])) {
+ if (empty($options['generate_getters'])) {
return '';
}
: " * @return {$t->type}\n";
$getters .= " * @access public\n";
$getters .= " */\n";
- $getters .= (substr(phpversion(),0,1) > 4) ? ' public '
+ $getters .= (substr(phpversion(), 0, 1) > 4) ? ' public '
: ' ';
$getters .= "function $methodName() {\n";
$getters .= " return \$this->{$t->name};\n";
* @return string
* @access public
*/
- function _generateLinkMethods($input)
+ public function _generateLinkMethods($input)
{
-
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$setters = '';
// only generate if option is set to true
// generate_link_methods true::
- if (empty($options['generate_link_methods'])) {
+ if (empty($options['generate_link_methods'])) {
//echo "skip lm? - not set";
return '';
}
$setters .= " * @access public\n";
$setters .= " */\n";
- $setters .= (substr(phpversion(),0,1) > 4) ? ' public '
+ $setters .= (substr(phpversion(), 0, 1) > 4) ? ' public '
: ' ';
$setters .= "function $methodName() {\n";
$setters .= " return \$this->link('$k', func_get_args());\n";
return $setters;
}
- /**
- * Generate setter methods for class definition
- *
- * @param string Existing class contents
- * @return string
- * @access public
- */
- function _generateSetters($input)
+ /**
+ * Generate setter methods for class definition
+ *
+ * @param string Existing class contents
+ * @return string
+ * @access public
+ */
+ public function _generateSetters($input)
{
-
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
+ $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
$setters = '';
// only generate if option is set to true
- if (empty($options['generate_setters'])) {
+ if (empty($options['generate_setters'])) {
return '';
}
$setters .= " * @param mixed input value\n";
$setters .= " * @access public\n";
$setters .= " */\n";
- $setters .= (substr(phpversion(),0,1) > 4) ? ' public '
+ $setters .= (substr(phpversion(), 0, 1) > 4) ? ' public '
: ' ';
$setters .= "function $methodName(\$value) {\n";
$setters .= " \$this->{$t->name} = \$value;\n";
* @return string
* @access public
*/
- function _generateTableFunction($def)
+ public function _generateTableFunction($def)
{
- $defines = explode(',','INT,STR,DATE,TIME,BOOL,TXT,BLOB,NOTNULL,MYSQLTIMESTAMP');
+ $defines = explode(',', 'INT,STR,DATE,TIME,BOOL,TXT,BLOB,NOTNULL,MYSQLTIMESTAMP');
$ret = "\n" .
" function table()\n" .
" {\n" .
" return array(\n";
- foreach($def as $k=>$v) {
+ foreach ($def as $k=>$v) {
$str = '0';
- foreach($defines as $dn) {
+ foreach ($defines as $dn) {
if ($v & constant('DB_DATAOBJECT_' . $dn)) {
$str .= ' + DB_DATAOBJECT_' . $dn;
}
}
if (strlen($str) > 1) {
- $str = substr($str,3); // strip the 0 +
+ $str = substr($str, 3); // strip the 0 +
}
// hopefully addslashes is good enough here!!!
$ret .= ' \''.addslashes($k).'\' => ' . $str . ",\n";
}
return $ret . " );\n" .
" }\n";
-
-
-
}
/**
* Generate keys Function - used generator_no_ini is set.
* @return string
* @access public
*/
- function _generateKeysFunction($def)
+ public function _generateKeysFunction($def)
{
-
$ret = "\n" .
" function keys()\n" .
" {\n" .
" return array(";
- foreach($def as $k=>$type) {
+ foreach ($def as $k=>$type) {
// hopefully addslashes is good enough here!!!
$ret .= '\''.addslashes($k).'\', ';
}
$ret = preg_replace('#, $#', '', $ret);
return $ret . ");\n" .
" }\n";
-
-
-
}
/**
* Generate sequenceKey Function - used generator_no_ini is set.
* @return string
* @access public
*/
- function _generateSequenceKeyFunction($def)
+ public function _generateSequenceKeyFunction($def)
{
//print_r($def);
if ($usekey !== false) {
if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table])) {
$usekey = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table];
- if (strpos($usekey,':') !== false) {
- list($usekey,$seqname) = explode(':',$usekey);
+ if (strpos($usekey, ':') !== false) {
+ list($usekey, $seqname) = explode(':', $usekey);
}
- }
+ }
- if (in_array($dbtype , array( 'mysql', 'mysqli', 'mssql', 'ifx')) &&
- ($table[$usekey] & DB_DATAOBJECT_INT) &&
+ if (in_array($dbtype, array( 'mysql', 'mysqli', 'mssql', 'ifx')) &&
+ ($table[$usekey] & DB_DATAOBJECT_INT) &&
isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
) {
// use native sequence keys.
" function sequenceKey() // keyname, use native, native name\n" .
" {\n" .
" return array(";
- foreach($ar as $v) {
+ foreach ($ar as $v) {
switch (gettype($v)) {
case 'boolean':
$ret .= ($v ? 'true' : 'false') . ', ';
$ret = preg_replace('#, $#', '', $ret);
return $ret . ");\n" .
" }\n";
-
}
/**
* Generate defaults Function - used generator_add_defaults or generator_no_ini is set.
* Only supports mysql and mysqli ... welcome ideas for more..
- *
+ *
*
* @param array table and key definition.
* @return string
* @access public
*/
- function _generateDefaultsFunction($table,$defs)
+ public function _generateDefaultsFunction($table, $defs)
{
$__DB= &$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
if (!in_array($__DB->phptype, array('mysql','mysqli'))) {
return; // cant handle non-mysql introspection for defaults.
}
- $options = PEAR::getStaticProperty('DB_DataObject','options');
+ $options = PEAR::getStaticProperty('DB_DataObject', 'options');
$db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
- $method = $db_driver == 'DB' ? 'getAll' : 'queryAll';
- $res = $__DB->$method('DESCRIBE ' . $table,DB_FETCHMODE_ASSOC);
+ $method = $db_driver == 'DB' ? 'getAll' : 'queryAll';
+ $res = $__DB->$method('DESCRIBE ' . $table, DB_FETCHMODE_ASSOC);
$defaults = array();
- foreach($res as $ar) {
+ foreach ($res as $ar) {
// this is initially very dumb... -> and it may mess up..
$type = $defs[$ar['Field']];
switch (true) {
- case (is_null( $ar['Default'])):
+ case (is_null($ar['Default'])):
$defaults[$ar['Field']] = 'null';
break;
- case ($type & DB_DATAOBJECT_DATE):
- case ($type & DB_DATAOBJECT_TIME):
+ case ($type & DB_DATAOBJECT_DATE):
+ case ($type & DB_DATAOBJECT_TIME):
case ($type & DB_DATAOBJECT_MYSQLTIMESTAMP): // not supported yet..
break;
- case ($type & DB_DATAOBJECT_BOOL):
+ case ($type & DB_DATAOBJECT_BOOL):
$defaults[$ar['Field']] = (int)(boolean) $ar['Default'];
break;
- case ($type & DB_DATAOBJECT_STR):
+ case ($type & DB_DATAOBJECT_STR):
$defaults[$ar['Field']] = "'" . addslashes($ar['Default']) . "'";
break;
" function defaults() // column default values \n" .
" {\n" .
" return array(\n";
- foreach($defaults as $k=>$v) {
+ foreach ($defaults as $k=>$v) {
$ret .= ' \''.addslashes($k).'\' => ' . $v . ",\n";
}
return $ret . " );\n" .
" }\n";
-
-
-
-
}
-
-
-
-
-
}
/**
*
* Example of how this could be used..
- *
+ *
* The lind method are now in here.
*
* Currenly only supports existing methods, and new 'link()' method
*
* @package DB_DataObject
*/
-class DB_DataObject_Links
+class DB_DataObject_Links
{
- /**
- * @property {DB_DataObject} do DataObject to apply this to.
- */
- var $do = false;
+ /**
+ * @property {DB_DataObject} do DataObject to apply this to.
+ */
+ public $do = false;
/**
* @property {Array|String} load What to load, 'all' or an array of properties. (default all)
*/
- var $load = 'all';
+ public $load = 'all';
/**
* @property {String|Boolean} scanf use part of column name as resulting
* property name. (default false)
*/
- var $scanf = false;
+ public $scanf = false;
/**
* @property {String|Boolean} printf use column name as sprintf for resulting property name..
* (default %s_link if apply is true, otherwise it is %s)
*/
- var $printf = false;
+ public $printf = false;
/**
* @property {Boolean} cached cache the result, so future queries will use cache rather
* than running the expensive sql query.
*/
- var $cached = false;
+ public $cached = false;
/**
* @property {Boolean} apply apply the result to this object, (default true)
*/
- var $apply = true;
+ public $apply = true;
//------------------------- RETURN ------------------------------------
/**
* @property {Array} links key value associative array of links.
*/
- var $links;
+ public $links;
/**
* @param {Array} cfg Configuration (basically properties of this object)
*/
- function DB_DataObject_Links($do,$cfg= array())
+ public function DB_DataObject_Links($do, $cfg= array())
{
// check if do is set!!!?
$this->do = $do;
- foreach($cfg as $k=>$v) {
+ foreach ($cfg as $k=>$v) {
$this->$k = $v;
}
-
-
}
/**
* return name from related object
*
* The relies on a <dbname>.links.ini file, unless you specify the arguments.
- *
+ *
* you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
*
*
* @access public
* @return mixed object on success false on failure or '0' when not linked
*/
- function getLink($field, $table= false, $link='')
+ public function getLink($field, $table= false, $link='')
{
-
static $cache = array();
// GUESS THE LINKED TABLE.. (if found - recursevly call self)
if ($table == false) {
-
-
$info = $this->linkInfo($field);
if ($info) {
- return $this->getLink($field, $info[0], $link === false ? $info[1] : $link );
+ return $this->getLink($field, $info[0], $link === false ? $info[1] : $link);
}
// no links defined.. - use borked BC method...
- // use the old _ method - this shouldnt happen if called via getLinks()
+ // use the old _ method - this shouldnt happen if called via getLinks()
if (!($p = strpos($field, '_'))) {
return false;
}
$table = substr($field, 0, $p);
return $this->getLink($field, $table);
-
-
-
}
$tn = is_string($table) ? $table : $table->tableName();
if (empty($this->do->$field) || $this->do->$field < 0) {
- return 0; // no record.
+ return 0; // no record.
}
if ($this->cached && isset($cache[$tn.':'. $link .':'. $this->do->$field])) {
- return $cache[$tn.':'. $link .':'. $this->do->$field];
+ return $cache[$tn.':'. $link .':'. $this->do->$field];
}
- $obj = is_string($table) ? $this->do->factory($tn) : $table;;
+ $obj = is_string($table) ? $this->do->factory($tn) : $table;
+ ;
- if (!is_a($obj,'DB_DataObject')) {
+ if (!is_a($obj, 'DB_DataObject')) {
$this->do->raiseError(
- "getLink:Could not find class for row $field, table $tn",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ "getLink:Could not find class for row $field, table $tn",
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
// -1 or 0 -- no referenced record..
$ret = false;
if ($link) {
-
if ($obj->get($link, $this->do->$field)) {
$ret = $obj;
}
- // this really only happens when no link config is set (old BC stuff)
- } else if ($obj->get($this->do->$field)) {
+ // this really only happens when no link config is set (old BC stuff)
+ } elseif ($obj->get($this->do->$field)) {
$ret= $obj;
-
}
if ($this->cached) {
$cache[$tn.':'. $link .':'. $this->do->$field] = $ret;
}
return $ret;
-
}
/**
* get link information for a field or field specification
* array(2) : 'field', 'table:remote_col' << just like the links.ini def.
* array(3) : 'field', $dataobject, 'remote_col' (handy for joinAdd to do nested joins.)
*
- * @param string|array $field or link spec to use.
+ * @param string|array $field or link spec to use.
* @return (false|array) array of dataobject and linked field or false.
*
*
*/
- function linkInfo($field)
+ public function linkInfo($field)
{
-
if (is_array($field)) {
if (count($field) == 3) {
// array with 3 args:
$field[2],
$field[0]
);
-
- }
- list($table,$link) = explode(':', $field[1]);
+ }
+ list($table, $link) = explode(':', $field[1]);
return array(
$this->do->factory($table),
$link,
$field[0]
);
-
}
// work out the link.. (classic way)
$links = $this->do->links();
if (empty($links) || !is_array($links)) {
-
return false;
}
if (!isset($links[$field])) {
-
return false;
}
- list($table,$link) = explode(':', $links[$field]);
+ list($table, $link) = explode(':', $links[$field]);
//??? needed???
- if ($p = strpos($field,".")) {
- $field = substr($field,0,$p);
+ if ($p = strpos($field, ".")) {
+ $field = substr($field, 0, $p);
}
return array(
$link,
$field
);
-
-
-
-
}
* eg.
* $link->link('company_id') returns getLink for the object
* if nothing is linked (it will return an empty dataObject)
- * $link->link('company_id', array(1)) - just sets the
+ * $link->link('company_id', array(1)) - just sets the
*
* also array as the field speck supports
* $link->link(array('company_id', 'company:id'))
- *
+ *
*
* @param string|array $field the field to fetch or link spec.
* @params array $args the arguments sent to the getter setter
* @return mixed true of false on set, the object on getter.
*
*/
- function link($field, $args = array())
+ public function link($field, $args = array())
{
$info = $this->linkInfo($field);
if (!$info) {
$this->do->raiseError(
- "getLink:Could not find link for row $field",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
+ "getLink:Could not find link for row $field",
+ DB_DATAOBJECT_ERROR_INVALIDCONFIG
+ );
return false;
}
$field = $info[2];
$ret = $this->getLink($field);
// nothing linked -- return new object..
return ($ret === 0) ? $info[0] : $ret;
-
}
$assign = is_array($args) ? $args[0] : $args;
// otherwise it's a set call..
- if (!is_a($assign , 'DB_DataObject')) {
-
+ if (!is_a($assign, 'DB_DataObject')) {
if (is_numeric($assign) && is_integer($assign * 1)) {
if ($assign > 0) {
-
if (!$info) {
return false;
}
// check that record exists..
- if (!$info[0]->get($info[1], $assign )) {
+ if (!$info[0]->get($info[1], $assign)) {
return false;
}
-
}
$this->do->$field = $assign ;
$this->do->$field = $assign->{$info[1]};
return true;
-
-
}
/**
* load related objects
* @return boolean , true on success
*/
- function applyLinks($format = '_%s')
+ public function applyLinks($format = '_%s')
{
// get table will load the options.
$loaded = array();
- if ($links) {
- foreach($links as $key => $match) {
- list($table,$link) = explode(':', $match);
+ if ($links) {
+ foreach ($links as $key => $match) {
+ list($table, $link) = explode(':', $match);
$k = sprintf($format, str_replace('.', '_', $key));
// makes sure that '.' is the end of the key;
- if ($p = strpos($key,'.')) {
- $key = substr($key, 0, $p);
+ if ($p = strpos($key, '.')) {
+ $key = substr($key, 0, $p);
}
$this->do->$k = $this->getLink($key, $table, $link);
if (is_object($this->do->$k)) {
- $loaded[] = $k;
+ $loaded[] = $k;
}
}
$this->do->_link_loaded = $loaded;
// this is the autonaming stuff..
// it sends the column name down to getLink and lets that sort it out..
// if there is a links file then it is not used!
- // IT IS DEPRECATED!!!! - DO NOT USE
- if (!is_null($links)) {
+ // IT IS DEPRECATED!!!! - DO NOT USE
+ if (!is_null($links)) {
return false;
}
$k =sprintf($format, $key);
$this->do->$k = $this->getLink($key);
if (is_object($this->do->$k)) {
- $loaded[] = $k;
+ $loaded[] = $k;
}
}
$this->do->_link_loaded = $loaded;
* <dbname>.links.ini file configuration (see the introduction on linking for details on this).
*
* You may also use this with all parameters to specify, the column and related table.
- *
+ *
* @access public
* @param string $field- either column or column.xxxxx
* @param string $table (optional) name of table to look up value in
* @param string $fval (optional)fetchall val DB_DataObject::fetchAll()
* @param string $fval (optional) fetchall method DB_DataObject::fetchAll()
* @return array - array of results (empty array on failure)
- *
+ *
* Example - Getting the related objects
- *
+ *
* $person = new DataObjects_Person;
* $person->get(12);
* $children = $person->getLinkArray('children');
- *
+ *
* echo 'There are ', count($children), ' descendant(s):<br />';
* foreach ($children as $child) {
* echo $child->name, '<br />';
* }
- *
+ *
*/
- function getLinkArray($field, $table = null, $fkey = false, $fval = false, $fmethod = false)
+ public function getLinkArray($field, $table = null, $fkey = false, $fval = false, $fmethod = false)
{
-
$ret = array();
- if (!$table) {
-
-
+ if (!$table) {
$links = $this->do->links();
if (is_array($links)) {
// failed..
return $ret;
}
- list($table,$link) = explode(':',$links[$field]);
- return $this->getLinkArray($field,$table);
- }
- if (!($p = strpos($field,'_'))) {
+ list($table, $link) = explode(':', $links[$field]);
+ return $this->getLinkArray($field, $table);
+ }
+ if (!($p = strpos($field, '_'))) {
return $ret;
}
- return $this->getLinkArray($field,substr($field,0,$p));
-
-
+ return $this->getLinkArray($field, substr($field, 0, $p));
}
$c = $this->do->factory($table);
- if (!is_object($c) || !is_a($c,'DB_DataObject')) {
+ if (!is_object($c) || !is_a($c, 'DB_DataObject')) {
$this->do->raiseError(
- "getLinkArray:Could not find class for row $field, table $table",
+ "getLinkArray:Could not find class for row $field, table $table",
DB_DATAOBJECT_ERROR_INVALIDCONFIG
);
return $ret;
$ret[] = clone($c);
}
return $ret;
- }
+ }
return $c->fetchAll($fkey, $fval, $fmethod);
-
-
}
-
-}
\ No newline at end of file
+}
// $Id: createTables.php 277015 2009-03-12 05:51:03Z alan_k $
//
-// since this version doesnt use overload,
+// since this version doesnt use overload,
// and I assume anyone using custom generators should add this..
-define('DB_DATAOBJECT_NO_OVERLOAD',1);
+define('DB_DATAOBJECT_NO_OVERLOAD', 1);
//require_once 'DB/DataObject/Generator.php';
require_once 'DB/DataObject/Generator.php';
}
$config = parse_ini_file($_SERVER['argv'][1], true);
-foreach($config as $class=>$values) {
- $options = &PEAR::getStaticProperty($class,'options');
+foreach ($config as $class=>$values) {
+ $options = &PEAR::getStaticProperty($class, 'options');
$options = $values;
}
-$options = &PEAR::getStaticProperty('DB_DataObject','options');
+$options = &PEAR::getStaticProperty('DB_DataObject', 'options');
if (empty($options)) {
PEAR::raiseError("\nERROR: could not read ini file\n\n", null, PEAR_ERROR_DIE);
exit;
$generator = new DB_DataObject_Generator;
$generator->start();
-
* The current default fetch mode
* @var integer
*/
- var $fetchmode = DB_FETCHMODE_ORDERED;
+ public $fetchmode = DB_FETCHMODE_ORDERED;
/**
* The name of the class into which results should be fetched when
*
* @var string
*/
- var $fetchmode_object_class = 'stdClass';
+ public $fetchmode_object_class = 'stdClass';
/**
* Was a connection present when the object was serialized()?
* @var bool
* @see DB_common::__sleep(), DB_common::__wake()
*/
- var $was_connected = null;
+ public $was_connected = null;
/**
* The most recently executed query
* @var string
*/
- var $last_query = '';
+ public $last_query = '';
/**
* Run-time configuration options
* @var array
* @see DB_common::setOption()
*/
- var $options = array(
+ public $options = array(
'result_buffering' => 500,
'persistent' => false,
'ssl' => false,
* @var array
* @since Property available since Release 1.7.0
*/
- var $last_parameters = array();
+ public $last_parameters = array();
/**
* The elements from each prepared statement
* @var array
*/
- var $prepare_tokens = array();
+ public $prepare_tokens = array();
/**
* The data types of the various elements in each prepared statement
* @var array
*/
- var $prepare_types = array();
+ public $prepare_types = array();
/**
* The prepared queries
* @var array
*/
- var $prepared_queries = array();
+ public $prepared_queries = array();
/**
* Flag indicating that the last query was a manipulation query.
* @access protected
* @var boolean
*/
- var $_last_query_manip = false;
+ public $_last_query_manip = false;
/**
* Flag indicating that the next query <em>must</em> be a manipulation
* @access protected
* @var boolean
*/
- var $_next_query_manip = false;
+ public $_next_query_manip = false;
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
$this->PEAR('DB_Error');
}
*
* @return array the array of properties names that should be saved
*/
- function __sleep()
+ public function __sleep()
{
if ($this->connection) {
// Don't disconnect(), people use serialize() for many reasons
*
* @return void
*/
- function __wakeup()
+ public function __wakeup()
{
if ($this->was_connected) {
$this->connect($this->dsn, $this->options['persistent']);
*
* @since Method available since Release 1.7.0
*/
- function __toString()
+ public function __toString()
{
$info = strtolower(get_class($this));
$info .= ': (phptype=' . $this->phptype .
*
* @deprecated Method deprecated in Release 1.7.0
*/
- function toString()
+ public function toString()
{
return $this->__toString();
}
* @see DB_common::quoteSmart(), DB_common::escapeSimple()
* @deprecated Method deprecated some time before Release 1.2
*/
- function quoteString($string)
+ public function quoteString($string)
{
$string = $this->quoteSmart($string);
if ($string{0} == "'") {
* @see DB_common::quoteSmart(), DB_common::escapeSimple()
* @deprecated Deprecated in release 1.6.0
*/
- function quote($string = null)
+ public function quote($string = null)
{
return $this->quoteSmart($string);
}
*
* @since Method available since Release 1.6.0
*/
- function quoteIdentifier($str)
+ public function quoteIdentifier($str)
{
return '"' . str_replace('"', '""', $str) . '"';
}
* @see DB_common::escapeSimple()
* @since Method available since Release 1.6.0
*/
- function quoteSmart($in)
+ public function quoteSmart($in)
{
if (is_int($in)) {
return $in;
return 'NULL';
} else {
if ($this->dbsyntax == 'access'
- && preg_match('/^#.+#$/', $in))
- {
+ && preg_match('/^#.+#$/', $in)) {
return $this->escapeSimple($in);
}
return "'" . $this->escapeSimple($in) . "'";
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteBoolean($boolean) {
+ public function quoteBoolean($boolean)
+ {
return $boolean ? '1' : '0';
}
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteFloat($float) {
+ public function quoteFloat($float)
+ {
return "'".$this->escapeSimple(str_replace(',', '.', strval(floatval($float))))."'";
}
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
return str_replace("'", "''", $str);
}
*
* @return bool whether this driver supports $feature
*/
- function provides($feature)
+ public function provides($feature)
{
return $this->features[$feature];
}
*
* @see DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC, DB_FETCHMODE_OBJECT
*/
- function setFetchMode($fetchmode, $object_class = 'stdClass')
+ public function setFetchMode($fetchmode, $object_class = 'stdClass')
{
switch ($fetchmode) {
case DB_FETCHMODE_OBJECT:
$this->fetchmode_object_class = $object_class;
+ // no break
case DB_FETCHMODE_ORDERED:
case DB_FETCHMODE_ASSOC:
$this->fetchmode = $fetchmode;
*
* @see DB_common::$options
*/
- function setOption($option, $value)
+ public function setOption($option, $value)
{
if (isset($this->options[$option])) {
$this->options[$option] = $value;
*
* @return mixed the option's value
*/
- function getOption($option)
+ public function getOption($option)
{
if (isset($this->options[$option])) {
return $this->options[$option];
*
* @see DB_common::execute()
*/
- function prepare($query)
+ public function prepare($query)
{
- $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
- PREG_SPLIT_DELIM_CAPTURE);
+ $tokens = preg_split(
+ '/((?<!\\\)[&?!])/',
+ $query,
+ -1,
+ PREG_SPLIT_DELIM_CAPTURE
+ );
$token = 0;
$types = array();
$newtokens = array();
*
* @uses DB_common::prepare(), DB_common::buildManipSQL()
*/
- function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT,
- $where = false)
- {
+ public function autoPrepare(
+ $table,
+ $table_fields,
+ $mode = DB_AUTOQUERY_INSERT,
+ $where = false
+ ) {
$query = $this->buildManipSQL($table, $table_fields, $mode, $where);
if (DB::isError($query)) {
return $query;
*
* @uses DB_common::autoPrepare(), DB_common::execute()
*/
- function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT,
- $where = false)
- {
- $sth = $this->autoPrepare($table, array_keys($fields_values), $mode,
- $where);
+ public function autoExecute(
+ $table,
+ $fields_values,
+ $mode = DB_AUTOQUERY_INSERT,
+ $where = false
+ ) {
+ $sth = $this->autoPrepare(
+ $table,
+ array_keys($fields_values),
+ $mode,
+ $where
+ );
if (DB::isError($sth)) {
return $sth;
}
$ret = $this->execute($sth, array_values($fields_values));
$this->freePrepared($sth);
return $ret;
-
}
// }}}
*
* @return string the sql query for autoPrepare()
*/
- function buildManipSQL($table, $table_fields, $mode, $where = false)
+ public function buildManipSQL($table, $table_fields, $mode, $where = false)
{
if (count($table_fields) == 0) {
return $this->raiseError(DB_ERROR_NEED_MORE_DATA);
*
* @see DB_common::prepare()
*/
- function &execute($stmt, $data = array())
+ public function &execute($stmt, $data = array())
{
$realquery = $this->executeEmulateQuery($stmt, $data);
if (DB::isError($realquery)) {
* @access protected
* @see DB_common::execute()
*/
- function executeEmulateQuery($stmt, $data = array())
+ public function executeEmulateQuery($stmt, $data = array())
{
$stmt = (int)$stmt;
$data = (array)$data;
*
* @see DB_common::prepare(), DB_common::execute()
*/
- function executeMultiple($stmt, $data)
+ public function executeMultiple($stmt, $data)
{
foreach ($data as $value) {
$res = $this->execute($stmt, $value);
*
* @see DB_common::prepare()
*/
- function freePrepared($stmt, $free_resource = true)
+ public function freePrepared($stmt, $free_resource = true)
{
$stmt = (int)$stmt;
if (isset($this->prepare_tokens[$stmt])) {
* @see DB_mysql::modifyQuery(), DB_oci8::modifyQuery(),
* DB_sqlite::modifyQuery()
*/
- function modifyQuery($query)
+ public function modifyQuery($query)
{
return $query;
}
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
return $query;
}
*
* @see DB_result, DB_common::prepare(), DB_common::execute()
*/
- function &query($query, $params = array())
+ public function &query($query, $params = array())
{
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*/
- function &limitQuery($query, $from, $count, $params = array())
+ public function &limitQuery($query, $from, $count, $params = array())
{
$query = $this->modifyLimitQuery($query, $from, $count, $params);
- if (DB::isError($query)){
+ if (DB::isError($query)) {
return $query;
}
$result = $this->query($query, $params);
* @return mixed the returned value of the query.
* A DB_Error object on failure.
*/
- function &getOne($query, $params = array())
+ public function &getOne($query, $params = array())
{
$params = (array)$params;
// modifyLimitQuery() would be nice here, but it causes BC issues
* @return array the first row of results as an array.
* A DB_Error object on failure.
*/
- function &getRow($query, $params = array(),
- $fetchmode = DB_FETCHMODE_DEFAULT)
- {
+ public function &getRow(
+ $query,
+ $params = array(),
+ $fetchmode = DB_FETCHMODE_DEFAULT
+ ) {
// compat check, the params and fetchmode parameters used to
// have the opposite order
if (!is_array($params)) {
*
* @see DB_common::query()
*/
- function &getCol($query, $col = 0, $params = array())
+ public function &getCol($query, $col = 0, $params = array())
{
$params = (array)$params;
if (sizeof($params) > 0) {
* @return array the associative array containing the query results.
* A DB_Error object on failure.
*/
- function &getAssoc($query, $force_array = false, $params = array(),
- $fetchmode = DB_FETCHMODE_DEFAULT, $group = false)
- {
+ public function &getAssoc(
+ $query,
+ $force_array = false,
+ $params = array(),
+ $fetchmode = DB_FETCHMODE_DEFAULT,
+ $group = false
+ ) {
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
*
* @return array the nested array. A DB_Error object on failure.
*/
- function &getAll($query, $params = array(),
- $fetchmode = DB_FETCHMODE_DEFAULT)
- {
+ public function &getAll(
+ $query,
+ $params = array(),
+ $fetchmode = DB_FETCHMODE_DEFAULT
+ ) {
// compat check, the params and fetchmode parameters used to
// have the opposite order
if (!is_array($params)) {
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function numRows($result)
+ public function numRows($result)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
* @see DB_common::createSequence(), DB_common::dropSequence(),
* DB_common::nextID(), DB_common::setOption()
*/
- function getSequenceName($sqn)
+ public function getSequenceName($sqn)
{
- return sprintf($this->getOption('seqname_format'),
- preg_replace('/[^a-z0-9_.]/i', '_', $sqn));
+ return sprintf(
+ $this->getOption('seqname_format'),
+ preg_replace('/[^a-z0-9_.]/i', '_', $sqn)
+ );
}
// }}}
* @see DB_common::createSequence(), DB_common::dropSequence(),
* DB_common::getSequenceName()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_common::nextID()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_common::nextID()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
*
* @see PEAR_Error
*/
- function &raiseError($code = DB_ERROR, $mode = null, $options = null,
- $userinfo = null, $nativecode = null, $dummy1 = null,
- $dummy2 = null)
- {
+ public function &raiseError(
+ $code = DB_ERROR,
+ $mode = null,
+ $options = null,
+ $userinfo = null,
+ $nativecode = null,
+ $dummy1 = null,
+ $dummy2 = null
+ ) {
// The error is yet a DB error object
if (is_object($code)) {
// because we the static PEAR::raiseError, our global
$mode = $this->_default_error_mode;
$options = $this->_default_error_options;
}
- $tmp = PEAR::raiseError($code, null, $mode, $options,
- null, null, true);
+ $tmp = PEAR::raiseError(
+ $code,
+ null,
+ $mode,
+ $options,
+ null,
+ null,
+ true
+ );
return $tmp;
}
$userinfo .= ' [DB Error: ' . DB::errorMessage($code) . ']';
}
- $tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo,
- 'DB_Error', true);
+ $tmp = PEAR::raiseError(
+ null,
+ $code,
+ $mode,
+ $options,
+ $userinfo,
+ 'DB_Error',
+ true
+ );
return $tmp;
}
*
* @return mixed the DBMS' error code. A DB_Error object on failure.
*/
- function errorNative()
+ public function errorNative()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
* current driver doesn't have a mapping for the
* $nativecode submitted.
*/
- function errorCode($nativecode)
+ public function errorCode($nativecode)
{
if (isset($this->errorcode_map[$nativecode])) {
return $this->errorcode_map[$nativecode];
*
* @see DB::errorMessage()
*/
- function errorMessage($dbcode)
+ public function errorMessage($dbcode)
{
return DB::errorMessage($this->errorcode_map[$dbcode]);
}
*
* @see DB_common::setOption()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
/*
* If the DB_<driver> class has a tableInfo() method, that one
*
* @deprecated Method deprecated some time before Release 1.2
*/
- function getTables()
+ public function getTables()
{
return $this->getListOf('tables');
}
* @return array an array listing the items sought.
* A DB DB_Error object on failure.
*/
- function getListOf($type)
+ public function getListOf($type)
{
$sql = $this->getSpecialQuery($type);
if ($sql === null) {
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
return $this->raiseError(DB_ERROR_UNSUPPORTED);
}
*
* @access public
*/
- function nextQueryIsManip($manip)
+ public function nextQueryIsManip($manip)
{
$this->_next_query_manip = $manip;
}
*
* @access protected
*/
- function _checkManip($query)
+ public function _checkManip($query)
{
if ($this->_next_query_manip || DB::isManip($query)) {
$this->_last_query_manip = true;
*
* @access protected
*/
- function _rtrimArrayValues(&$array)
+ public function _rtrimArrayValues(&$array)
{
foreach ($array as $key => $value) {
if (is_string($value)) {
*
* @access protected
*/
- function _convertNullArrayValuesToEmpty(&$array)
+ public function _convertNullArrayValuesToEmpty(&$array)
{
foreach ($array as $key => $value) {
if (is_null($value)) {
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'dbase';
+ public $phptype = 'dbase';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'dbase';
+ public $dbsyntax = 'dbase';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => false,
'new_link' => false,
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
);
/**
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* A means of emulating result resources
* @var array
*/
- var $res_row = array();
+ public $res_row = array();
/**
* The quantity of results so far
*
* @var integer
*/
- var $result = 0;
+ public $result = 0;
/**
* Maps dbase data type id's to human readable strings
* @var array
* @since Property available since Release 1.7.0
*/
- var $types = array(
+ public $types = array(
'C' => 'character',
'D' => 'date',
'L' => 'boolean',
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('dbase')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
if (!file_exists($dsn['database'])) {
$this->dsn['mode'] = 2;
if (empty($dsn['fields']) || !is_array($dsn['fields'])) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- 'the dbase file does not exist and '
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ 'the dbase file does not exist and '
. 'it could not be created because '
. 'the "fields" element of the DSN '
- . 'is not properly set');
+ . 'is not properly set'
+ );
}
- $this->connection = @dbase_create($dsn['database'],
- $dsn['fields']);
+ $this->connection = @dbase_create(
+ $dsn['database'],
+ $dsn['fields']
+ );
if (!$this->connection) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- 'the dbase file does not exist and '
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ 'the dbase file does not exist and '
. 'the attempt to create it failed: '
- . $php_errormsg);
+ . $php_errormsg
+ );
}
} else {
if (!isset($this->dsn['mode'])) {
$this->dsn['mode'] = 0;
}
- $this->connection = @dbase_open($dsn['database'],
- $this->dsn['mode']);
+ $this->connection = @dbase_open(
+ $dsn['database'],
+ $this->dsn['mode']
+ );
if (!$this->connection) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
}
return DB_OK;
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @dbase_close($this->connection);
$this->connection = null;
// }}}
// {{{ &query()
- function &query($query = null)
+ public function &query($query = null)
{
// emulate result resources
$this->res_row[(int)$this->result] = 0;
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum === null) {
$rownum = $this->res_row[(int)$result]++;
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return true;
}
*
* @see DB_result::numCols()
*/
- function numCols($foo)
+ public function numCols($foo)
{
return @dbase_numfields($this->connection);
}
*
* @see DB_result::numRows()
*/
- function numRows($foo)
+ public function numRows($foo)
{
return @dbase_numrecords($this->connection);
}
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteBoolean($boolean) {
+ public function quoteBoolean($boolean)
+ {
return $boolean ? 'T' : 'F';
}
* @see DB_common::tableInfo()
* @since Method available since Release 1.7.0
*/
- function tableInfo($result = null, $mode = null)
+ public function tableInfo($result = null, $mode = null)
{
if (function_exists('dbase_get_header_info')) {
$id = @dbase_get_header_info($this->connection);
if (!$id && $php_errormsg) {
- return $this->raiseError(DB_ERROR,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
} else {
/*
*/
$db = @fopen($this->dsn['database'], 'r');
if (!$db) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
$id = array();
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'fbsql';
+ public $phptype = 'fbsql';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'fbsql';
+ public $dbsyntax = 'fbsql';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'alter',
'new_link' => false,
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
22 => DB_ERROR_SYNTAX,
85 => DB_ERROR_ALREADY_EXISTS,
108 => DB_ERROR_SYNTAX,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('fbsql')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
$ini = ini_get('track_errors');
$php_errormsg = '';
if ($ini) {
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
} else {
@ini_set('track_errors', 1);
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
@ini_set('track_errors', $ini);
}
if (!$this->connection) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
if ($dsn['database']) {
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @fbsql_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$this->last_query = $query;
$query = $this->modifyQuery($query);
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return @fbsql_next_result($result);
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@fbsql_data_seek($result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? fbsql_free_result($result) : false;
}
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff=false)
+ public function autoCommit($onoff=false)
{
if ($onoff) {
$this->query("SET COMMIT TRUE");
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
@fbsql_commit($this->connection);
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
@fbsql_rollback($this->connection);
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @fbsql_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @fbsql_num_rows($result);
if ($rows === null) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->_last_query_manip) {
$result = @fbsql_affected_rows($this->connection);
$result = 0;
}
return $result;
- }
+ }
// }}}
// {{{ nextId()
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_fbsql::createSequence(), DB_fbsql::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
do {
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_fbsql::nextID(), DB_fbsql::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$seqname = $this->getSequenceName($seq_name);
$res = $this->query('CREATE TABLE ' . $seqname
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_fbsql::nextID(), DB_fbsql::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name)
. ' RESTRICT');
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
if (DB::isManip($query) || $this->_next_query_manip) {
- return preg_replace('/^([\s(])*SELECT/i',
- "\\1SELECT TOP($count)", $query);
+ return preg_replace(
+ '/^([\s(])*SELECT/i',
+ "\\1SELECT TOP($count)",
+ $query
+ );
} else {
- return preg_replace('/([\s(])*SELECT/i',
- "\\1SELECT TOP($from, $count)", $query);
+ return preg_replace(
+ '/([\s(])*SELECT/i',
+ "\\1SELECT TOP($from, $count)",
+ $query
+ );
}
}
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteBoolean($boolean) {
+ public function quoteBoolean($boolean)
+ {
return $boolean ? 'TRUE' : 'FALSE';
}
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteFloat($float) {
+ public function quoteFloat($float)
+ {
return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
}
* @see DB_common::raiseError(),
* DB_fbsql::errorNative(), DB_common::errorCode()
*/
- function fbsqlRaiseError($errno = null)
+ public function fbsqlRaiseError($errno = null)
{
if ($errno === null) {
$errno = $this->errorCode(fbsql_errno($this->connection));
}
- return $this->raiseError($errno, null, null, null,
- @fbsql_error($this->connection));
+ return $this->raiseError(
+ $errno,
+ null,
+ null,
+ null,
+ @fbsql_error($this->connection)
+ );
}
// }}}
*
* @return int the DBMS' error code
*/
- function errorNative()
+ public function errorNative()
{
return @fbsql_errno($this->connection);
}
*
* @see DB_common::tableInfo()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @fbsql_list_fields($this->dsn['database'],
- $result, $this->connection);
+ $id = @fbsql_list_fields(
+ $this->dsn['database'],
+ $result,
+ $this->connection
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
. ' "table_type" = \'VIEW\''
. ' AND "schema_name" = current_schema';
case 'users':
- return 'SELECT "user_name" from information_schema.users';
+ return 'SELECT "user_name" from information_schema.users';
case 'functions':
return 'SELECT "routine_name" FROM'
. ' information_schema.psm_routines'
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'ibase';
+ public $phptype = 'ibase';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'ibase';
+ public $dbsyntax = 'ibase';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => false,
'new_link' => false,
'numrows' => 'emulate',
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
-104 => DB_ERROR_SYNTAX,
-150 => DB_ERROR_ACCESS_VIOLATION,
-151 => DB_ERROR_ACCESS_VIOLATION,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var integer
* @access private
*/
- var $affected = 0;
+ public $affected = 0;
/**
* Should data manipulation queries be committed automatically?
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The prepared statement handle from the most recently executed statement
*
* @var resource
*/
- var $last_stmt;
+ public $last_stmt;
/**
* Is the given prepared statement a data manipulation query?
* @var array
* @access private
*/
- var $manip_query = array();
+ public $manip_query = array();
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('interbase')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @ibase_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
if ($this->dsn['dbsyntax'] == 'firebird') {
- $query = preg_replace('/^([\s(])*SELECT/i',
- "SELECT FIRST $count SKIP $from", $query);
+ $query = preg_replace(
+ '/^([\s(])*SELECT/i',
+ "SELECT FIRST $count SKIP $from",
+ $query
+ );
}
return $query;
}
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
return $this->ibaseRaiseError(DB_ERROR_NOT_CAPABLE);
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? ibase_free_result($result) : false;
}
// }}}
// {{{ freeQuery()
- function freeQuery($query)
+ public function freeQuery($query)
{
return is_resource($query) ? ibase_free_query($query) : false;
}
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if (is_integer($this->affected)) {
return $this->affected;
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @ibase_num_fields($result);
if (!$cols) {
* @param string $query query to be prepared
* @return mixed DB statement resource on success. DB_Error on failure.
*/
- function prepare($query)
+ public function prepare($query)
{
- $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
- PREG_SPLIT_DELIM_CAPTURE);
+ $tokens = preg_split(
+ '/((?<!\\\)[&?!])/',
+ $query,
+ -1,
+ PREG_SPLIT_DELIM_CAPTURE
+ );
$token = 0;
$types = array();
$newquery = '';
* @see DB_ibase::prepare()
* @access public
*/
- function &execute($stmt, $data = array())
+ public function &execute($stmt, $data = array())
{
$data = (array)$data;
$this->last_parameters = $data;
*
* @see DB_ibase::prepare()
*/
- function freePrepared($stmt, $free_resource = true)
+ public function freePrepared($stmt, $free_resource = true)
{
if (!is_resource($stmt)) {
return false;
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
$this->autocommit = $onoff ? 1 : 0;
return DB_OK;
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
return @ibase_commit($this->connection);
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
return @ibase_rollback($this->connection);
}
// }}}
// {{{ transactionInit()
- function transactionInit($trans_args = 0)
+ public function transactionInit($trans_args = 0)
{
return $trans_args
? @ibase_trans($trans_args, $this->connection)
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_ibase::createSequence(), DB_ibase::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$sqn = strtoupper($this->getSequenceName($seq_name));
$repeat = 0;
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_ibase::nextID(), DB_ibase::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$sqn = strtoupper($this->getSequenceName($seq_name));
$this->pushErrorHandling(PEAR_ERROR_RETURN);
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_ibase::nextID(), DB_ibase::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DELETE FROM RDB$GENERATORS '
. "WHERE RDB\$GENERATOR_NAME='"
*
* @access private
*/
- function _ibaseFieldFlags($field_name, $table_name)
+ public function _ibaseFieldFlags($field_name, $table_name)
{
$sql = 'SELECT R.RDB$CONSTRAINT_TYPE CTYPE'
.' FROM RDB$INDEX_SEGMENTS I'
* @see DB_common::raiseError(),
* DB_ibase::errorNative(), DB_ibase::errorCode()
*/
- function &ibaseRaiseError($errno = null)
+ public function &ibaseRaiseError($errno = null)
{
if ($errno === null) {
$errno = $this->errorCode($this->errorNative());
*
* @since Method available since Release 1.7.0
*/
- function errorNative()
+ public function errorNative()
{
if (function_exists('ibase_errcode')) {
return @ibase_errcode();
}
- if (preg_match('/^Dynamic SQL Error SQL error code = ([0-9-]+)/i',
- @ibase_errmsg(), $m)) {
+ if (preg_match(
+ '/^Dynamic SQL Error SQL error code = ([0-9-]+)/i',
+ @ibase_errmsg(),
+ $m
+ )) {
return (int)$m[1];
}
return null;
*
* @since Method available since Release 1.7.0
*/
- function errorCode($nativecode = null)
+ public function errorCode($nativecode = null)
{
if (isset($this->errorcode_map[$nativecode])) {
return $this->errorcode_map[$nativecode];
*
* @see DB_common::tableInfo()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @ibase_query($this->connection,
- "SELECT * FROM $result WHERE 1=0");
+ $id = @ibase_query(
+ $this->connection,
+ "SELECT * FROM $result WHERE 1=0"
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'ifx';
+ public $phptype = 'ifx';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'ifx';
+ public $dbsyntax = 'ifx';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'emulate',
'new_link' => false,
'numrows' => 'emulate',
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
'-201' => DB_ERROR_SYNTAX,
'-206' => DB_ERROR_NOSUCHTABLE,
'-217' => DB_ERROR_NOSUCHFIELD,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The quantity of transactions begun
* @var integer
* @access private
*/
- var $transaction_opcount = 0;
+ public $transaction_opcount = 0;
/**
* The number of rows affected by a data manipulation query
* @var integer
* @access private
*/
- var $affected = 0;
+ public $affected = 0;
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('informix') &&
- !PEAR::loadExtension('Informix'))
- {
+ !PEAR::loadExtension('Informix')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @ifx_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->_last_query_manip) {
return $this->affected;
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if (($rownum !== null) && ($rownum < 0)) {
return null;
}
$arr = $order;
} elseif ($fetchmode == DB_FETCHMODE_ASSOC &&
- $this->options['portability'] & DB_PORTABILITY_LOWERCASE)
- {
+ $this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
$arr = array_change_key_case($arr, CASE_LOWER);
}
if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
if (!$cols = @ifx_num_fields($result)) {
return $this->ifxRaiseError();
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? ifx_free_result($result) : false;
}
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = true)
+ public function autoCommit($onoff = true)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if ($this->transaction_opcount > 0) {
$result = @ifx_query('COMMIT WORK', $this->connection);
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if ($this->transaction_opcount > 0) {
$result = @ifx_query('ROLLBACK WORK', $this->connection);
* @see DB_common::raiseError(),
* DB_ifx::errorNative(), DB_ifx::errorCode()
*/
- function ifxRaiseError($errno = null)
+ public function ifxRaiseError($errno = null)
{
if ($errno === null) {
$errno = $this->errorCode(ifx_error());
}
- return $this->raiseError($errno, null, null, null,
- $this->errorNative());
+ return $this->raiseError(
+ $errno,
+ null,
+ null,
+ null,
+ $this->errorNative()
+ );
}
// }}}
*
* @return string the DBMS' error code and message
*/
- function errorNative()
+ public function errorNative()
{
return @ifx_error() . ' ' . @ifx_errormsg();
}
* @return int a portable DB error code, or DB_ERROR if this DB
* implementation has no mapping for the given error code.
*/
- function errorCode($nativecode)
+ public function errorCode($nativecode)
{
if (preg_match('/SQLCODE=(.*)]/', $nativecode, $match)) {
$code = $match[1];
* @see DB_common::tableInfo()
* @since Method available since Release 1.6.0
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @ifx_query("SELECT * FROM $result WHERE 1=0",
- $this->connection);
+ $id = @ifx_query(
+ "SELECT * FROM $result WHERE 1=0",
+ $this->connection
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'msql';
+ public $phptype = 'msql';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'msql';
+ public $dbsyntax = 'msql';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'emulate',
'new_link' => false,
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
);
/**
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var resource
* @access private
*/
- var $_result;
+ public $_result;
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
* Example of how to connect:
* <code>
* require_once 'DB.php';
- *
+ *
* // $dsn = 'msql://hostname/dbname'; // use a TCP connection
* $dsn = 'msql:///dbname'; // use a socket
* $options = array(
* 'portability' => DB_PORTABILITY_ALL,
* );
- *
+ *
* $db = DB::connect($dsn, $options);
* if (PEAR::isError($db)) {
* die($db->getMessage());
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('msql')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
$ini = ini_get('track_errors');
$php_errormsg = '';
if ($ini) {
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
} else {
@ini_set('track_errors', 1);
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
@ini_set('track_errors', $ini);
}
if (!$this->connection) {
if (($err = @msql_error()) != '') {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $err);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $err
+ );
} else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @msql_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$this->last_query = $query;
$query = $this->modifyQuery($query);
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@msql_data_seek($result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? msql_free_result($result) : false;
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @msql_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @msql_num_rows($result);
if ($rows === false) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if (!$this->_result) {
return 0;
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_msql::createSequence(), DB_msql::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
$repeat = false;
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_msql::nextID(), DB_msql::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$seqname = $this->getSequenceName($seq_name);
$res = $this->query('CREATE TABLE ' . $seqname
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_msql::nextID(), DB_msql::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
* @see DB_common::quoteIdentifier()
* @since Method available since Release 1.7.0
*/
- function quoteIdentifier($str)
+ public function quoteIdentifier($str)
{
return $this->raiseError(DB_ERROR_UNSUPPORTED);
}
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteFloat($float) {
+ public function quoteFloat($float)
+ {
return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
}
* @see DB_common::quoteSmart()
* @since Method available since Release 1.7.0
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
return addslashes($str);
}
* @see DB_common::raiseError(),
* DB_msql::errorNative(), DB_msql::errorCode()
*/
- function msqlRaiseError($errno = null)
+ public function msqlRaiseError($errno = null)
{
$native = $this->errorNative();
if ($errno === null) {
*
* @return string the DBMS' error message
*/
- function errorNative()
+ public function errorNative()
{
return @msql_error();
}
*
* @return integer the error number from a DB_ERROR* constant
*/
- function errorCode($errormsg)
+ public function errorCode($errormsg)
{
static $error_regexps;
*
* @see DB_common::setOption()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @msql_query("SELECT * FROM $result",
- $this->connection);
+ $id = @msql_query(
+ "SELECT * FROM $result",
+ $this->connection
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'databases':
$id = @msql_list_dbs($this->connection);
break;
case 'tables':
- $id = @msql_list_tables($this->dsn['database'],
- $this->connection);
+ $id = @msql_list_tables(
+ $this->dsn['database'],
+ $this->connection
+ );
break;
default:
return null;
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'mssql';
+ public $phptype = 'mssql';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'mssql';
+ public $dbsyntax = 'mssql';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'emulate',
'new_link' => false,
'numrows' => true,
* @var array
*/
// XXX Add here error codes ie: 'S100E' => DB_ERROR_SYNTAX
- var $errorcode_map = array(
+ public $errorcode_map = array(
102 => DB_ERROR_SYNTAX,
110 => DB_ERROR_VALUE_COUNT_ON_ROW,
155 => DB_ERROR_NOSUCHFIELD,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The quantity of transactions begun
* @var integer
* @access private
*/
- var $transaction_opcount = 0;
+ public $transaction_opcount = 0;
/**
* The database specified in the DSN
* @var string
* @access private
*/
- var $_db = null;
+ public $_db = null;
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('mssql') && !PEAR::loadExtension('sybase')
- && !PEAR::loadExtension('sybase_ct'))
- {
+ && !PEAR::loadExtension('sybase_ct')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
}
$this->connection = @call_user_func_array($connect_function, $params);
if (!$this->connection) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- @mssql_get_last_message());
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ @mssql_get_last_message()
+ );
}
if ($dsn['database']) {
if (!@mssql_select_db($dsn['database'], $this->connection)) {
- return $this->raiseError(DB_ERROR_NODBSELECTED,
- null, null, null,
- @mssql_get_last_message());
+ return $this->raiseError(
+ DB_ERROR_NODBSELECTED,
+ null,
+ null,
+ null,
+ @mssql_get_last_message()
+ );
}
$this->_db = $dsn['database'];
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @mssql_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return @mssql_next_result($result);
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@mssql_data_seek($result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? mssql_free_result($result) : false;
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @mssql_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @mssql_num_rows($result);
if ($rows === false) {
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if ($this->transaction_opcount > 0) {
if (!@mssql_select_db($this->_db, $this->connection)) {
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if ($this->transaction_opcount > 0) {
if (!@mssql_select_db($this->_db, $this->connection)) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->_last_query_manip) {
$res = @mssql_query('select @@rowcount', $this->connection);
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_mssql::createSequence(), DB_mssql::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
if (!@mssql_select_db($this->_db, $this->connection)) {
$result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
$this->popErrorHandling();
if ($ondemand && DB::isError($result) &&
- ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
- {
+ ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE)) {
$repeat = 1;
$result = $this->createSequence($seq_name);
if (DB::isError($result)) {
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_mssql::nextID(), DB_mssql::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
return $this->query('CREATE TABLE '
. $this->getSequenceName($seq_name)
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_mssql::nextID(), DB_mssql::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
return str_replace(
array("'", "\\\r\n", "\\\n"),
* @see DB_common::quoteIdentifier()
* @since Method available since Release 1.6.0
*/
- function quoteIdentifier($str)
+ public function quoteIdentifier($str)
{
return '[' . str_replace(']', ']]', $str) . ']';
}
* @see DB_common::raiseError(),
* DB_mssql::errorNative(), DB_mssql::errorCode()
*/
- function mssqlRaiseError($code = null)
+ public function mssqlRaiseError($code = null)
{
$message = @mssql_get_last_message();
if (!$code) {
$code = $this->errorNative();
}
- return $this->raiseError($this->errorCode($code, $message),
- null, null, null, "$code - $message");
+ return $this->raiseError(
+ $this->errorCode($code, $message),
+ null,
+ null,
+ null,
+ "$code - $message"
+ );
}
// }}}
*
* @return int the DBMS' error code
*/
- function errorNative()
+ public function errorNative()
{
$res = @mssql_query('select @@ERROR as ErrorCode', $this->connection);
if (!$res) {
* @return integer an error number from a DB error constant
* @see errorNative()
*/
- function errorCode($nativecode = null, $msg = '')
+ public function errorCode($nativecode = null, $msg = '')
{
if (!$nativecode) {
$nativecode = $this->errorNative();
}
if (isset($this->errorcode_map[$nativecode])) {
if ($nativecode == 3701
- && preg_match('/Cannot drop the index/i', $msg))
- {
+ && preg_match('/Cannot drop the index/i', $msg)) {
return DB_ERROR_NOT_FOUND;
}
return $this->errorcode_map[$nativecode];
*
* @see DB_common::tableInfo()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
if (!@mssql_select_db($this->_db, $this->connection)) {
return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
}
- $id = @mssql_query("SELECT * FROM $result WHERE 1=0",
- $this->connection);
+ $id = @mssql_query(
+ "SELECT * FROM $result WHERE 1=0",
+ $this->connection
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
for ($i = 0; $i < $count; $i++) {
if ($got_string) {
- $flags = $this->_mssql_field_flags($result,
- @mssql_field_name($id, $i));
+ $flags = $this->_mssql_field_flags(
+ $result,
+ @mssql_field_name($id, $i)
+ );
if (DB::isError($flags)) {
return $flags;
}
* @access private
* @author Joern Barthel <j_barthel@web.de>
*/
- function _mssql_field_flags($table, $column)
+ public function _mssql_field_flags($table, $column)
{
static $tableName = null;
static $flags = array();
if ($table != $tableName) {
-
$flags = array();
$tableName = $table;
* @access private
* @author Joern Barthel <j_barthel@web.de>
*/
- function _add_flag(&$array, $value)
+ public function _add_flag(&$array, $value)
{
if (!is_array($array)) {
$array = array($value);
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'mysql';
+ public $phptype = 'mysql';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'mysql';
+ public $dbsyntax = 'mysql';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'alter',
'new_link' => '4.2.0',
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
1004 => DB_ERROR_CANNOT_CREATE,
1005 => DB_ERROR_CANNOT_CREATE,
1006 => DB_ERROR_CANNOT_CREATE,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The quantity of transactions begun
* @var integer
* @access private
*/
- var $transaction_opcount = 0;
+ public $transaction_opcount = 0;
/**
* The database specified in the DSN
* @var string
* @access private
*/
- var $_db = '';
+ public $_db = '';
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('mysql')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
if (!$persistent) {
if (isset($dsn['new_link'])
- && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true))
- {
+ && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true)) {
$params[] = true;
} else {
$params[] = false;
$ini = ini_get('track_errors');
$php_errormsg = '';
if ($ini) {
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
} else {
@ini_set('track_errors', 1);
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
@ini_set('track_errors', $ini);
}
if (!$this->connection) {
if (($err = @mysql_error()) != '') {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $err);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $err
+ );
} else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @mysql_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
*
* @return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@mysql_data_seek($result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? mysql_free_result($result) : false;
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @mysql_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @mysql_num_rows($result);
if ($rows === null) {
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if ($this->transaction_opcount > 0) {
if ($this->_db) {
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if ($this->transaction_opcount > 0) {
if ($this->_db) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->_last_query_manip) {
return @mysql_affected_rows($this->connection);
} else {
return 0;
}
- }
+ }
// }}}
// {{{ nextId()
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_mysql::createSequence(), DB_mysql::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
do {
}
// We know what the result will be, so no need to try again
return 1;
-
} elseif ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE)
- {
+ $result->getCode() == DB_ERROR_NOSUCHTABLE) {
// ONDEMAND TABLE CREATION
$result = $this->createSequence($seq_name);
if (DB::isError($result)) {
} else {
$repeat = 1;
}
-
} elseif (DB::isError($result) &&
- $result->getCode() == DB_ERROR_ALREADY_EXISTS)
- {
+ $result->getCode() == DB_ERROR_ALREADY_EXISTS) {
// BACKWARDS COMPAT
// see _BCsequence() comment
$result = $this->_BCsequence($seqname);
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_mysql::nextID(), DB_mysql::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$seqname = $this->getSequenceName($seq_name);
$res = $this->query('CREATE TABLE ' . $seqname
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_mysql::nextID(), DB_mysql::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
*
* @access private
*/
- function _BCsequence($seqname)
+ public function _BCsequence($seqname)
{
// Obtain a user-level lock... this will release any previous
// application locks, but unlike LOCK TABLES, it does not abort
* @see DB_common::quoteIdentifier()
* @since Method available since Release 1.6.0
*/
- function quoteIdentifier($str)
+ public function quoteIdentifier($str)
{
return '`' . str_replace('`', '``', $str) . '`';
}
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
if (function_exists('mysql_real_escape_string')) {
return @mysql_real_escape_string($str, $this->connection);
* @access protected
* @see DB_common::setOption()
*/
- function modifyQuery($query)
+ public function modifyQuery($query)
{
if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
// "DELETE FROM table" gives 0 affected rows in MySQL.
// This little hack lets you know how many rows were deleted.
if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
+ $query = preg_replace(
+ '/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
+ 'DELETE FROM \1 WHERE 1=1',
+ $query
+ );
}
}
return $query;
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
if (DB::isManip($query) || $this->_next_query_manip) {
return $query . " LIMIT $count";
* @see DB_common::raiseError(),
* DB_mysql::errorNative(), DB_common::errorCode()
*/
- function mysqlRaiseError($errno = null)
+ public function mysqlRaiseError($errno = null)
{
if ($errno === null) {
if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
}
$errno = $this->errorCode(mysql_errno($this->connection));
}
- return $this->raiseError($errno, null, null, null,
- @mysql_errno($this->connection) . ' ** ' .
- @mysql_error($this->connection));
+ return $this->raiseError(
+ $errno,
+ null,
+ null,
+ null,
+ @mysql_errno($this->connection) . ' ** ' .
+ @mysql_error($this->connection)
+ );
}
// }}}
*
* @return int the DBMS' error code
*/
- function errorNative()
+ public function errorNative()
{
return @mysql_errno($this->connection);
}
*
* @see DB_common::tableInfo()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
// Fix for bug #11580.
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @mysql_query("SELECT * FROM $result LIMIT 0",
- $this->connection);
+ $id = @mysql_query(
+ "SELECT * FROM $result LIMIT 0",
+ $this->connection
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'mysqli';
+ public $phptype = 'mysqli';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'mysqli';
+ public $dbsyntax = 'mysqli';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'alter',
'new_link' => false,
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
1004 => DB_ERROR_CANNOT_CREATE,
1005 => DB_ERROR_CANNOT_CREATE,
1006 => DB_ERROR_CANNOT_CREATE,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The quantity of transactions begun
* @var integer
* @access private
*/
- var $transaction_opcount = 0;
+ public $transaction_opcount = 0;
/**
* The database specified in the DSN
* @var string
* @access private
*/
- var $_db = '';
+ public $_db = '';
/**
* Array for converting MYSQLI_*_FLAG constants to text values
* @access public
* @since Property available since Release 1.6.5
*/
- var $mysqli_flags = array(
+ public $mysqli_flags = array(
MYSQLI_NOT_NULL_FLAG => 'not_null',
MYSQLI_PRI_KEY_FLAG => 'primary_key',
MYSQLI_UNIQUE_KEY_FLAG => 'unique_key',
* @access public
* @since Property available since Release 1.6.5
*/
- var $mysqli_types = array(
+ public $mysqli_types = array(
MYSQLI_TYPE_DECIMAL => 'decimal',
MYSQLI_TYPE_TINY => 'tinyint',
MYSQLI_TYPE_SHORT => 'int',
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
* Example of how to connect using SSL:
* <code>
* require_once 'DB.php';
- *
+ *
* $dsn = array(
* 'phptype' => 'mysqli',
* 'username' => 'someuser',
* 'capath' => '/path/to/ca/dir',
* 'cipher' => 'AES',
* );
- *
+ *
* $options = array(
* 'ssl' => true,
* );
- *
+ *
* $db = DB::connect($dsn, $options);
* if (PEAR::isError($db)) {
* die($db->getMessage());
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('mysqli')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
empty($dsn['cipher']) ? null : $dsn['cipher']
);
if ($this->connection = @mysqli_real_connect(
- $init,
- $dsn['hostspec'],
- $dsn['username'],
- $dsn['password'],
- $dsn['database'],
- $dsn['port'],
- $dsn['socket']))
- {
+ $init,
+ $dsn['hostspec'],
+ $dsn['username'],
+ $dsn['password'],
+ $dsn['database'],
+ $dsn['port'],
+ $dsn['socket']
+ )) {
$this->connection = $init;
}
} else {
if (!$this->connection) {
if (($err = @mysqli_connect_error()) != '') {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $err);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $err
+ );
} else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @mysqli_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
* @return false
* @access public
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@mysqli_data_seek($result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
if (! $result instanceof mysqli_result) {
return false;
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @mysqli_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @mysqli_num_rows($result);
if ($rows === null) {
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if ($this->transaction_opcount > 0) {
if ($this->_db) {
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if ($this->transaction_opcount > 0) {
if ($this->_db) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->_last_query_manip) {
return @mysqli_affected_rows($this->connection);
} else {
return 0;
}
- }
+ }
// }}}
// {{{ nextId()
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_mysqli::createSequence(), DB_mysqli::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
do {
}
// We know what the result will be, so no need to try again
return 1;
-
} elseif ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE)
- {
+ $result->getCode() == DB_ERROR_NOSUCHTABLE) {
// ONDEMAND TABLE CREATION
$result = $this->createSequence($seq_name);
// First ID of a newly created sequence is 1
return 1;
}
-
} elseif (DB::isError($result) &&
- $result->getCode() == DB_ERROR_ALREADY_EXISTS)
- {
+ $result->getCode() == DB_ERROR_ALREADY_EXISTS) {
// BACKWARDS COMPAT
// see _BCsequence() comment
$result = $this->_BCsequence($seqname);
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_mysqli::nextID(), DB_mysqli::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$seqname = $this->getSequenceName($seq_name);
$res = $this->query('CREATE TABLE ' . $seqname
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_mysql::nextID(), DB_mysql::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
*
* @access private
*/
- function _BCsequence($seqname)
+ public function _BCsequence($seqname)
{
// Obtain a user-level lock... this will release any previous
// application locks, but unlike LOCK TABLES, it does not abort
* @see DB_common::quoteIdentifier()
* @since Method available since Release 1.6.0
*/
- function quoteIdentifier($str)
+ public function quoteIdentifier($str)
{
return '`' . str_replace('`', '``', $str) . '`';
}
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
return @mysqli_real_escape_string($this->connection, $str);
}
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
if (DB::isManip($query) || $this->_next_query_manip) {
return $query . " LIMIT $count";
* @see DB_common::raiseError(),
* DB_mysqli::errorNative(), DB_common::errorCode()
*/
- function mysqliRaiseError($errno = null)
+ public function mysqliRaiseError($errno = null)
{
if ($errno === null) {
if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
}
$errno = $this->errorCode(mysqli_errno($this->connection));
}
- return $this->raiseError($errno, null, null, null,
- @mysqli_errno($this->connection) . ' ** ' .
- @mysqli_error($this->connection));
+ return $this->raiseError(
+ $errno,
+ null,
+ null,
+ null,
+ @mysqli_errno($this->connection) . ' ** ' .
+ @mysqli_error($this->connection)
+ );
}
// }}}
*
* @return int the DBMS' error code
*/
- function errorNative()
+ public function errorNative()
{
return @mysqli_errno($this->connection);
}
*
* @see DB_common::setOption()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
// Fix for bug #11580.
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @mysqli_query($this->connection,
- "SELECT * FROM $result LIMIT 0");
+ $id = @mysqli_query(
+ $this->connection,
+ "SELECT * FROM $result LIMIT 0"
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'oci8';
+ public $phptype = 'oci8';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'oci8';
+ public $dbsyntax = 'oci8';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'alter',
'new_link' => '5.0.0',
'numrows' => 'subquery',
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
1 => DB_ERROR_CONSTRAINT,
900 => DB_ERROR_SYNTAX,
904 => DB_ERROR_NOSUCHFIELD,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* Stores the $data passed to execute() in the oci8 driver
* @var array
* @access private
*/
- var $_data = array();
+ public $_data = array();
/**
* The result or statement handle from the most recently executed query
* @var resource
*/
- var $last_stmt;
+ public $last_stmt;
/**
* Is the given prepared statement a data manipulation query?
* @var array
* @access private
*/
- var $manip_query = array();
+ public $manip_query = array();
/**
* Store of prepared SQL queries.
* @var array
* @access private
*/
- var $_prepared_queries = array();
+ public $_prepared_queries = array();
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('oci8')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
if (function_exists('oci_connect')) {
if (isset($dsn['new_link'])
- && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true))
- {
+ && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true)) {
$connect_function = 'oci_new_connect';
} else {
$connect_function = $persistent ? 'oci_pconnect'
}
$char = empty($dsn['charset']) ? null : $dsn['charset'];
- $this->connection = @$connect_function($dsn['username'],
- $dsn['password'],
- $db,
- $char);
+ $this->connection = @$connect_function(
+ $dsn['username'],
+ $dsn['password'],
+ $db,
+ $char
+ );
$error = OCIError();
if (!empty($error) && $error['code'] == 12541) {
// Couldn't find TNS listener. Try direct connection.
- $this->connection = @$connect_function($dsn['username'],
- $dsn['password'],
- null,
- $char);
+ $this->connection = @$connect_function(
+ $dsn['username'],
+ $dsn['password'],
+ null,
+ $char
+ );
}
} else {
$connect_function = $persistent ? 'OCIPLogon' : 'OCILogon';
if ($db) {
- $this->connection = @$connect_function($dsn['username'],
- $dsn['password'],
- $db);
+ $this->connection = @$connect_function(
+ $dsn['username'],
+ $dsn['password'],
+ $db
+ );
} elseif ($dsn['username'] || $dsn['password']) {
- $this->connection = @$connect_function($dsn['username'],
- $dsn['password']);
+ $this->connection = @$connect_function(
+ $dsn['username'],
+ $dsn['password']
+ );
}
}
if (!$this->connection) {
$error = OCIError();
$error = (is_array($error)) ? $error['message'] : null;
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $error);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $error
+ );
}
return DB_OK;
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
if (function_exists('oci_close')) {
$ret = @oci_close($this->connection);
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$this->_data = array();
$this->last_parameters = array();
return $this->oci8RaiseError();
}
if ($this->autocommit) {
- $success = @OCIExecute($result,OCI_COMMIT_ON_SUCCESS);
+ $success = @OCIExecute($result, OCI_COMMIT_ON_SUCCESS);
} else {
- $success = @OCIExecute($result,OCI_DEFAULT);
+ $success = @OCIExecute($result, OCI_DEFAULT);
}
if (!$success) {
return $this->oci8RaiseError($result);
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $moredata = @OCIFetchInto($result,$arr,OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS);
+ $moredata = @OCIFetchInto($result, $arr, OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS);
if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE &&
- $moredata)
- {
+ $moredata) {
$arr = array_change_key_case($arr, CASE_LOWER);
}
} else {
- $moredata = OCIFetchInto($result,$arr,OCI_RETURN_NULLS+OCI_RETURN_LOBS);
+ $moredata = OCIFetchInto($result, $arr, OCI_RETURN_NULLS+OCI_RETURN_LOBS);
}
if (!$moredata) {
return null;
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? OCIFreeStatement($result) : false;
}
*
* @see DB_oci8::prepare()
*/
- function freePrepared($stmt, $free_resource = true)
+ public function freePrepared($stmt, $free_resource = true)
{
if (!is_resource($stmt)) {
return false;
*
* @see DB_result::numRows(), DB_common::setOption()
*/
- function numRows($result)
+ public function numRows($result)
{
// emulate numRows for Oracle. yuck.
if ($this->options['portability'] & DB_PORTABILITY_NUMROWS &&
- $result === $this->last_stmt)
- {
+ $result === $this->last_stmt) {
$countquery = 'SELECT COUNT(*) FROM ('.$this->last_query.')';
$save_query = $this->last_query;
$save_stmt = $this->last_stmt;
$this->last_stmt = $save_stmt;
if (DB::isError($count) ||
- DB::isError($row = $count->fetchRow(DB_FETCHMODE_ORDERED)))
- {
+ DB::isError($row = $count->fetchRow(DB_FETCHMODE_ORDERED))) {
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @OCINumCols($result);
if (!$cols) {
*
* @see DB_oci8::execute()
*/
- function prepare($query)
+ public function prepare($query)
{
- $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
- PREG_SPLIT_DELIM_CAPTURE);
+ $tokens = preg_split(
+ '/((?<!\\\)[&?!])/',
+ $query,
+ -1,
+ PREG_SPLIT_DELIM_CAPTURE
+ );
$binds = count($tokens) - 1;
$token = 0;
$types = array();
*
* @see DB_oci8::prepare()
*/
- function &execute($stmt, $data = array())
+ public function &execute($stmt, $data = array())
{
$data = (array)$data;
$this->last_parameters = $data;
$tmp = $this->oci8RaiseError($stmt);
return $tmp;
}
- $this->last_query = preg_replace("/:bind$i(?!\d)/",
- $this->quoteSmart($data[$key]), $this->last_query, 1);
+ $this->last_query = preg_replace(
+ "/:bind$i(?!\d)/",
+ $this->quoteSmart($data[$key]),
+ $this->last_query,
+ 1
+ );
$i++;
}
if ($this->autocommit) {
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
- $this->autocommit = (bool)$onoff;;
+ $this->autocommit = (bool)$onoff;
+ ;
return DB_OK;
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
$result = @OCICommit($this->connection);
if (!$result) {
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
$result = @OCIRollback($this->connection);
if (!$result) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->last_stmt === false) {
return $this->oci8RaiseError();
*
* @access protected
*/
- function modifyQuery($query)
+ public function modifyQuery($query)
{
if (preg_match('/^\s*SELECT/i', $query) &&
!preg_match('/\sFROM\s/i', $query)) {
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
// Let Oracle return the name of the columns instead of
// coding a "home" SQL parser
$ncols = OCINumCols($result);
$cols = array();
- for ( $i = 1; $i <= $ncols; $i++ ) {
+ for ($i = 1; $i <= $ncols; $i++) {
$cols[] = '"' . OCIColumnName($result, $i) . '"';
}
$fields = implode(', ', $cols);
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_oci8::createSequence(), DB_oci8::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
$repeat = 0;
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_oci8::nextID(), DB_oci8::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
return $this->query('CREATE SEQUENCE '
. $this->getSequenceName($seq_name));
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_oci8::nextID(), DB_oci8::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP SEQUENCE '
. $this->getSequenceName($seq_name));
* @see DB_common::raiseError(),
* DB_oci8::errorNative(), DB_oci8::errorCode()
*/
- function oci8RaiseError($errno = null)
+ public function oci8RaiseError($errno = null)
{
if ($errno === null) {
$error = @OCIError($this->connection);
- return $this->raiseError($this->errorCode($error['code']),
- null, null, null, $error['message']);
+ return $this->raiseError(
+ $this->errorCode($error['code']),
+ null,
+ null,
+ null,
+ $error['message']
+ );
} elseif (is_resource($errno)) {
$error = @OCIError($errno);
- return $this->raiseError($this->errorCode($error['code']),
- null, null, null, $error['message']);
+ return $this->raiseError(
+ $this->errorCode($error['code']),
+ null,
+ null,
+ null,
+ $error['message']
+ );
}
return $this->raiseError($this->errorCode($errno));
}
* @return int the DBMS' error code. FALSE if the code could not be
* determined
*/
- function errorNative()
+ public function errorNative()
{
if (is_resource($this->last_stmt)) {
$error = @OCIError($this->last_stmt);
*
* @see DB_common::tableInfo()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
$case_func = 'strtolower';
$res['num_fields'] = $i;
}
@OCIFreeStatement($stmt);
-
} else {
if (isset($result->result)) {
/*
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteFloat($float) {
+ public function quoteFloat($float)
+ {
return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'odbc';
+ public $phptype = 'odbc';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'sql92';
+ public $dbsyntax = 'sql92';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'emulate',
'new_link' => false,
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
'01004' => DB_ERROR_TRUNCATED,
'07001' => DB_ERROR_MISMATCH,
'21S01' => DB_ERROR_VALUE_COUNT_ON_ROW,
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var integer
* @access private
*/
- var $affected = 0;
+ public $affected = 0;
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('odbc')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
$connect_function = $persistent ? 'odbc_pconnect' : 'odbc_connect';
if (empty($dsn['cursor'])) {
- $this->connection = @$connect_function($odbcdsn, $dsn['username'],
- $dsn['password']);
+ $this->connection = @$connect_function(
+ $odbcdsn,
+ $dsn['username'],
+ $dsn['password']
+ );
} else {
- $this->connection = @$connect_function($odbcdsn, $dsn['username'],
- $dsn['password'],
- $dsn['cursor']);
+ $this->connection = @$connect_function(
+ $odbcdsn,
+ $dsn['username'],
+ $dsn['password'],
+ $dsn['cursor']
+ );
}
if (!is_resource($this->connection)) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $this->errorNative());
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $this->errorNative()
+ );
}
return DB_OK;
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$err = @odbc_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$this->last_query = $query;
$query = $this->modifyQuery($query);
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return @odbc_next_result($result);
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
$arr = array();
if ($rownum !== null) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? odbc_free_result($result) : false;
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @odbc_num_fields($result);
if (!$cols) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if (empty($this->affected)) { // In case of SELECT stms
return 0;
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$nrows = @odbc_num_rows($result);
if ($nrows == -1) {
* @see DB_common::quoteIdentifier()
* @since Method available since Release 1.6.0
*/
- function quoteIdentifier($str)
+ public function quoteIdentifier($str)
{
switch ($this->dsn['dbsyntax']) {
case 'access':
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_odbc::createSequence(), DB_odbc::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
$repeat = 0;
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_odbc::nextID(), DB_odbc::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
return $this->query('CREATE TABLE '
. $this->getSequenceName($seq_name)
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_odbc::nextID(), DB_odbc::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
if (!@odbc_autocommit($this->connection, $onoff)) {
return $this->odbcRaiseError();
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if (!@odbc_commit($this->connection)) {
return $this->odbcRaiseError();
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if (!@odbc_rollback($this->connection)) {
return $this->odbcRaiseError();
* @see DB_common::raiseError(),
* DB_odbc::errorNative(), DB_common::errorCode()
*/
- function odbcRaiseError($errno = null)
+ public function odbcRaiseError($errno = null)
{
if ($errno === null) {
switch ($this->dbsyntax) {
}
foreach ($error_regexps as $regexp => $code) {
if (preg_match($regexp, $errormsg)) {
- return $this->raiseError($code,
- null, null, null,
- $native_code . ' ' . $errormsg);
+ return $this->raiseError(
+ $code,
+ null,
+ null,
+ null,
+ $native_code . ' ' . $errormsg
+ );
}
}
$errno = DB_ERROR;
$errno = $this->errorCode(odbc_error($this->connection));
}
}
- return $this->raiseError($errno, null, null, null,
- $this->errorNative());
+ return $this->raiseError(
+ $errno,
+ null,
+ null,
+ null,
+ $this->errorNative()
+ );
}
// }}}
*
* @return string the DBMS' error code and message
*/
- function errorNative()
+ public function errorNative()
{
if (!is_resource($this->connection)) {
return @odbc_error() . ' ' . @odbc_errormsg();
* @see DB_common::tableInfo()
* @since Method available since Release 1.7.0
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
* @see DB_common::getListOf()
* @since Method available since Release 1.7.0
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'databases':
$res = @odbc_data_source($this->connection, SQL_FETCH_FIRST);
if (is_array($res)) {
$out = array($res['server']);
- while($res = @odbc_data_source($this->connection,
- SQL_FETCH_NEXT))
- {
+ while ($res = @odbc_data_source(
+ $this->connection,
+ SQL_FETCH_NEXT
+ )) {
$out[] = $res['server'];
}
return $out;
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'pgsql';
+ public $phptype = 'pgsql';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'pgsql';
+ public $dbsyntax = 'pgsql';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'alter',
'new_link' => '4.3.0',
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
);
/**
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The quantity of transactions begun
* @var integer
* @access private
*/
- var $transaction_opcount = 0;
+ public $transaction_opcount = 0;
/**
* The number of rows affected by a data manipulation query
* @var integer
*/
- var $affected = 0;
+ public $affected = 0;
/**
* The current row being looked at in fetchInto()
* @var array
* @access private
*/
- var $row = array();
+ public $row = array();
/**
* The number of rows in a given result set
* @var array
* @access private
*/
- var $_num_rows = array();
+ public $_num_rows = array();
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
* Example of connecting to a new link via a socket:
* <code>
* require_once 'DB.php';
- *
+ *
* $dsn = 'pgsql://user:pass@unix(/tmp)/dbname?new_link=true';
* $options = array(
* 'portability' => DB_PORTABILITY_ALL,
* );
- *
+ *
* $db = DB::connect($dsn, $options);
* if (PEAR::isError($db)) {
* die($db->getMessage());
*
* @link http://www.postgresql.org/docs/current/static/libpq.html#LIBPQ-CONNECT
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('pgsql')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
}
if (isset($dsn['new_link'])
- && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true))
- {
+ && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true)) {
if (version_compare(phpversion(), '4.3.0', '>=')) {
$params[] = PGSQL_CONNECT_FORCE_NEW;
}
$ini = ini_get('track_errors');
$php_errormsg = '';
if ($ini) {
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
} else {
@ini_set('track_errors', 1);
- $this->connection = @call_user_func_array($connect_function,
- $params);
+ $this->connection = @call_user_func_array(
+ $connect_function,
+ $params
+ );
@ini_set('track_errors', $ini);
}
if (!$this->connection) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
return DB_OK;
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @pg_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
if ($ismanip) {
$this->affected = @pg_affected_rows($result);
return DB_OK;
- } elseif (preg_match('/^\s*\(*\s*(SELECT|EXPLAIN|FETCH|SHOW|WITH)\s/si',
- $query))
- {
+ } elseif (preg_match(
+ '/^\s*\(*\s*(SELECT|EXPLAIN|FETCH|SHOW|WITH)\s/si',
+ $query
+ )) {
$this->row[(int)$result] = 0; // reset the row counter.
$numrows = $this->numRows($result);
if (is_object($numrows)) {
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
$result_int = (int)$result;
$rownum = ($rownum !== null) ? $rownum : $this->row[$result_int];
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
if (is_resource($result)) {
unset($this->row[(int)$result]);
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteBoolean($boolean) {
+ public function quoteBoolean($boolean)
+ {
return $boolean ? 'TRUE' : 'FALSE';
}
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
if (function_exists('pg_escape_string')) {
/* This fixes an undocumented BC break in PHP 5.2.0 which changed
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @pg_numfields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @pg_numrows($result);
if ($rows === null) {
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if ($this->transaction_opcount > 0) {
// (disabled) hack to shut up error messages from libpq.a
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if ($this->transaction_opcount > 0) {
$result = @pg_exec($this->connection, 'abort;');
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
return $this->affected;
}
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_pgsql::createSequence(), DB_pgsql::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
$repeat = false;
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_pgsql::nextID(), DB_pgsql::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$seqname = $this->getSequenceName($seq_name);
$result = $this->query("CREATE SEQUENCE ${seqname}");
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_pgsql::nextID(), DB_pgsql::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP SEQUENCE '
. $this->getSequenceName($seq_name));
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
return "$query LIMIT $count OFFSET $from";
}
* @see DB_common::raiseError(),
* DB_pgsql::errorNative(), DB_pgsql::errorCode()
*/
- function pgsqlRaiseError($errno = null)
+ public function pgsqlRaiseError($errno = null)
{
$native = $this->errorNative();
if (!$native) {
/**
* Gets the DBMS' native error message produced by the last query
*
- * {@internal Error messages are used instead of error codes
+ * {@internal Error messages are used instead of error codes
* in order to support older versions of PostgreSQL.}}
*
* @return string the DBMS' error message
*/
- function errorNative()
+ public function errorNative()
{
return @pg_errormessage($this->connection);
}
* @param string $errormsg error message returned from the database
* @return integer an error number from a DB error constant
*/
- function errorCode($errormsg)
+ public function errorCode($errormsg)
{
static $error_regexps;
if (!isset($error_regexps)) {
*
* @see DB_common::tableInfo()
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
*
* @access private
*/
- function _pgFieldFlags($resource, $num_field, $table_name)
+ public function _pgFieldFlags($resource, $num_field, $table_name)
{
$field_name = @pg_fieldname($resource, $num_field);
if (in_array($num_field + 1, $keys)) {
$flags .= ($row[0] == 't' && $row[1] == 'f') ? 'unique_key ' : '';
$flags .= ($row[1] == 't') ? 'primary_key ' : '';
- if (count($keys) > 1)
+ if (count($keys) > 1) {
$flags .= 'multiple_key ';
+ }
}
}
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
*
* @access protected
*/
- function _checkManip($query)
+ public function _checkManip($query)
{
return (preg_match('/^\s*(SAVEPOINT|RELEASE)\s+/i', $query)
|| parent::_checkManip($query));
}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'sqlite';
+ public $phptype = 'sqlite';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'sqlite';
+ public $dbsyntax = 'sqlite';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'alter',
'new_link' => false,
'numrows' => true,
*
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
);
/**
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
*
* @var array
*/
- var $keywords = array (
+ public $keywords = array(
'BLOB' => '',
'BOOLEAN' => '',
'CHARACTER' => '',
* @var string
* @access private
*/
- var $_lasterror = '';
+ public $_lasterror = '';
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
* Example of connecting to a database in read-only mode:
* <code>
* require_once 'DB.php';
- *
+ *
* $dsn = 'sqlite:///path/and/name/of/db/file?mode=0400';
* $options = array(
* 'portability' => DB_PORTABILITY_ALL,
* );
- *
+ *
* $db = DB::connect($dsn, $options);
* if (PEAR::isError($db)) {
* die($db->getMessage());
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('sqlite')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
}
if (!isset($dsn['mode']) ||
- !is_numeric($dsn['mode']))
- {
+ !is_numeric($dsn['mode'])) {
$mode = 0644;
} else {
$mode = octdec($dsn['mode']);
$php_errormsg = '';
if (!$this->connection = @$connect_function($dsn['database'])) {
- return $this->raiseError(DB_ERROR_NODBSELECTED,
- null, null, null,
- $php_errormsg);
+ return $this->raiseError(
+ DB_ERROR_NODBSELECTED,
+ null,
+ null,
+ null,
+ $php_errormsg
+ );
}
return DB_OK;
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @sqlite_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
*
* @return bool true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@sqlite_seek($this->result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult(&$result)
+ public function freeResult(&$result)
{
// XXX No native free?
if (!is_resource($result)) {
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @sqlite_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @sqlite_num_rows($result);
if ($rows === null) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
return @sqlite_changes($this->connection);
}
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_sqlite::nextID(), DB_sqlite::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_sqlite::nextID(), DB_sqlite::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
$seqname = $this->getSequenceName($seq_name);
$query = 'CREATE TABLE ' . $seqname .
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_sqlite::createSequence(), DB_sqlite::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
return $id;
}
} elseif ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE)
- {
+ $result->getCode() == DB_ERROR_NOSUCHTABLE) {
$result = $this->createSequence($seq_name);
if (DB::isError($result)) {
return $this->raiseError($result);
* @return mixed an array on an unspecified key, integer on a passed
* arg and false at a stats error
*/
- function getDbFileStats($arg = '')
+ public function getDbFileStats($arg = '')
{
$stats = stat($this->dsn['database']);
if ($stats == false) {
* @since Method available since Release 1.6.1
* @see DB_common::escapeSimple()
*/
- function escapeSimple($str)
+ public function escapeSimple($str)
{
return @sqlite_escape_string($str);
}
*
* @access protected
*/
- function modifyLimitQuery($query, $from, $count, $params = array())
+ public function modifyLimitQuery($query, $from, $count, $params = array())
{
return "$query LIMIT $count OFFSET $from";
}
* @access protected
* @see DB_common::setOption()
*/
- function modifyQuery($query)
+ public function modifyQuery($query)
{
if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
+ $query = preg_replace(
+ '/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
+ 'DELETE FROM \1 WHERE 1=1',
+ $query
+ );
}
}
return $query;
* @see DB_common::raiseError(),
* DB_sqlite::errorNative(), DB_sqlite::errorCode()
*/
- function sqliteRaiseError($errno = null)
+ public function sqliteRaiseError($errno = null)
{
$native = $this->errorNative();
if ($errno === null) {
*
* @return string the DBMS' error message
*/
- function errorNative()
+ public function errorNative()
{
return $this->_lasterror;
}
*
* @return integer the DB error number
*/
- function errorCode($errormsg)
+ public function errorCode($errormsg)
{
static $error_regexps;
* @see DB_common::tableInfo()
* @since Method available since Release 1.7.0
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
* Probably received a table name.
* Create a result resource identifier.
*/
- $id = @sqlite_array_query($this->connection,
- "PRAGMA table_info('$result');",
- SQLITE_ASSOC);
+ $id = @sqlite_array_query(
+ $this->connection,
+ "PRAGMA table_info('$result');",
+ SQLITE_ASSOC
+ );
$got_string = true;
} else {
$this->last_query = '';
- return $this->raiseError(DB_ERROR_NOT_CAPABLE, null, null, null,
- 'This DBMS can not obtain tableInfo' .
- ' from result sets');
+ return $this->raiseError(
+ DB_ERROR_NOT_CAPABLE,
+ null,
+ null,
+ null,
+ 'This DBMS can not obtain tableInfo' .
+ ' from result sets'
+ );
}
if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
if (strpos($id[$i]['type'], '(') !== false) {
$bits = explode('(', $id[$i]['type']);
$type = $bits[0];
- $len = rtrim($bits[1],')');
+ $len = rtrim($bits[1], ')');
} else {
$type = $id[$i]['type'];
$len = 0;
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type, $args = array())
+ public function getSpecialQuery($type, $args = array())
{
if (!is_array($args)) {
- return $this->raiseError('no key specified', null, null, null,
- 'Argument has to be an array.');
+ return $this->raiseError(
+ 'no key specified',
+ null,
+ null,
+ null,
+ 'Argument has to be an array.'
+ );
}
switch ($type) {
* c-basic-offset: 4
* End:
*/
-
-?>
/** the name of the table (or view, if the backend database supports
updates in views) we hold data from */
- var $_table = null;
+ public $_table = null;
/** which column(s) in the table contains primary keys, can be a
string for single-column primary keys, or an array of strings
for multiple-column primary keys */
- var $_keycolumn = null;
+ public $_keycolumn = null;
/** DB connection handle used for all transactions */
- var $_dbh = null;
+ public $_dbh = null;
/** an assoc with the names of database fields stored as properties
in this object */
- var $_properties = array();
+ public $_properties = array();
/** an assoc with the names of the properties in this object that
have been changed since they were fetched from the database */
- var $_changes = array();
+ public $_changes = array();
/** flag that decides if data in this object can be changed.
objects that don't have their table's key column in their
property lists will be flagged as read-only. */
- var $_readonly = false;
+ public $_readonly = false;
/** function or method that implements a validator for fields that
are set, this validator function returns true if the field is
valid, false if not */
- var $_validator = null;
+ public $_validator = null;
// }}}
// {{{ constructor
* a reference to this object
*
*/
- function __construct($table, $keycolumn, &$dbh, $validator = null)
+ public function __construct($table, $keycolumn, &$dbh, $validator = null)
{
$this->PEAR('DB_Error');
$this->_table = $table;
*
* @access private
*/
- function _makeWhere($keyval = null)
+ public function _makeWhere($keyval = null)
{
if (is_array($this->_keycolumn)) {
if ($keyval === null) {
*
* @return int DB_OK on success, a DB error if not
*/
- function setup($keyval)
+ public function setup($keyval)
{
$whereclause = $this->_makeWhere($keyval);
$query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause;
return $row;
}
if (!$row) {
- return $this->raiseError(null, DB_ERROR_NOT_FOUND, null, null,
- $query, null, true);
+ return $this->raiseError(
+ null,
+ DB_ERROR_NOT_FOUND,
+ null,
+ null,
+ $query,
+ null,
+ true
+ );
}
foreach ($row as $key => $value) {
$this->_properties[$key] = true;
* Create a new (empty) row in the configured table for this
* object.
*/
- function insert($newpk)
+ public function insert($newpk)
{
if (is_array($this->_keycolumn)) {
$primarykey = $this->_keycolumn;
* Output a simple description of this DB_storage object.
* @return string object description
*/
- function toString()
+ public function toString()
{
$info = strtolower(get_class($this));
$info .= " (table=";
/**
* Dump the contents of this object to "standard output".
*/
- function dump()
+ public function dump()
{
foreach ($this->_properties as $prop => $foo) {
print "$prop = ";
* of properties/columns
* @return object a new instance of DB_storage or a subclass of it
*/
- function &create($table, &$data)
+ public function &create($table, &$data)
{
$classname = strtolower(get_class($this));
$obj = new $classname($table);
* key column was not found among the columns returned by $query),
* or another DB error code in case of errors.
*/
-// XXX commented out for now
-/*
- function loadFromQuery($query, $params = null)
- {
- if (sizeof($this->_properties)) {
- if (sizeof($this->_changes)) {
- $this->store();
- $this->_changes = array();
+ // XXX commented out for now
+ /*
+ function loadFromQuery($query, $params = null)
+ {
+ if (sizeof($this->_properties)) {
+ if (sizeof($this->_changes)) {
+ $this->store();
+ $this->_changes = array();
+ }
+ $this->_properties = array();
}
- $this->_properties = array();
- }
- $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
- if (DB::isError($rowdata)) {
- return $rowdata;
- }
- reset($rowdata);
- $found_keycolumn = false;
- while (list($key, $value) = each($rowdata)) {
- if ($key == $this->_keycolumn) {
- $found_keycolumn = true;
+ $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
+ if (DB::isError($rowdata)) {
+ return $rowdata;
}
- $this->_properties[$key] = true;
- $this->$key = &$value;
- unset($value); // have to unset, or all properties will
- // refer to the same value
- }
- if (!$found_keycolumn) {
- $this->_readonly = true;
- return DB_WARNING_READ_ONLY;
+ reset($rowdata);
+ $found_keycolumn = false;
+ while (list($key, $value) = each($rowdata)) {
+ if ($key == $this->_keycolumn) {
+ $found_keycolumn = true;
+ }
+ $this->_properties[$key] = true;
+ $this->$key = &$value;
+ unset($value); // have to unset, or all properties will
+ // refer to the same value
+ }
+ if (!$found_keycolumn) {
+ $this->_readonly = true;
+ return DB_WARNING_READ_ONLY;
+ }
+ return DB_OK;
}
- return DB_OK;
- }
- */
+ */
// }}}
// {{{ set()
/**
* Modify an attriute value.
*/
- function set($property, $newvalue)
+ public function set($property, $newvalue)
{
// only change if $property is known and object is not
// read-only
if ($this->_readonly) {
- return $this->raiseError(null, DB_WARNING_READ_ONLY, null,
- null, null, null, true);
+ return $this->raiseError(
+ null,
+ DB_WARNING_READ_ONLY,
+ null,
+ null,
+ null,
+ null,
+ true
+ );
}
if (@isset($this->_properties[$property])) {
if (empty($this->_validator)) {
$valid = true;
} else {
- $valid = @call_user_func($this->_validator,
- $this->_table,
- $property,
- $newvalue,
- $this->$property,
- $this);
+ $valid = @call_user_func(
+ $this->_validator,
+ $this->_table,
+ $property,
+ $newvalue,
+ $this->$property,
+ $this
+ );
}
if ($valid) {
$this->$property = $newvalue;
$this->_changes[$property]++;
}
} else {
- return $this->raiseError(null, DB_ERROR_INVALID, null,
- null, "invalid field: $property",
- null, true);
+ return $this->raiseError(
+ null,
+ DB_ERROR_INVALID,
+ null,
+ null,
+ "invalid field: $property",
+ null,
+ true
+ );
}
return true;
}
- return $this->raiseError(null, DB_ERROR_NOSUCHFIELD, null,
- null, "unknown field: $property",
- null, true);
+ return $this->raiseError(
+ null,
+ DB_ERROR_NOSUCHFIELD,
+ null,
+ null,
+ "unknown field: $property",
+ null,
+ true
+ );
}
// }}}
* @return attribute contents, or null if the attribute name is
* unknown
*/
- function &get($property)
+ public function &get($property)
{
// only return if $property is known
if (isset($this->_properties[$property])) {
* Destructor, calls DB_storage::store() if there are changes
* that are to be kept.
*/
- function _DB_storage()
+ public function _DB_storage()
{
if (sizeof($this->_changes)) {
$this->store();
*
* @return DB_OK or a DB error
*/
- function store()
+ public function store()
{
$params = array();
$vars = array();
*
* @return mixed DB_OK or a DB error
*/
- function remove()
+ public function remove()
{
if ($this->_readonly) {
- return $this->raiseError(null, DB_WARNING_READ_ONLY, null,
- null, null, null, true);
+ return $this->raiseError(
+ null,
+ DB_WARNING_READ_ONLY,
+ null,
+ null,
+ null,
+ null,
+ true
+ );
}
$query = 'DELETE FROM ' . $this->_table .' WHERE '.
$this->_makeWhere();
* c-basic-offset: 4
* End:
*/
-
-?>
* The DB driver type (mysql, oci8, odbc, etc.)
* @var string
*/
- var $phptype = 'sybase';
+ public $phptype = 'sybase';
/**
* The database syntax variant to be used (db2, access, etc.), if any
* @var string
*/
- var $dbsyntax = 'sybase';
+ public $dbsyntax = 'sybase';
/**
* The capabilities of this DB implementation
*
* @var array
*/
- var $features = array(
+ public $features = array(
'limit' => 'emulate',
'new_link' => false,
'numrows' => true,
* A mapping of native error codes to DB error codes
* @var array
*/
- var $errorcode_map = array(
+ public $errorcode_map = array(
);
/**
* The raw database connection created by PHP
* @var resource
*/
- var $connection;
+ public $connection;
/**
* The DSN information for connecting to a database
* @var array
*/
- var $dsn = array();
+ public $dsn = array();
/**
* @var bool
* @access private
*/
- var $autocommit = true;
+ public $autocommit = true;
/**
* The quantity of transactions begun
* @var integer
* @access private
*/
- var $transaction_opcount = 0;
+ public $transaction_opcount = 0;
/**
* The database specified in the DSN
* @var string
* @access private
*/
- var $_db = '';
+ public $_db = '';
// }}}
*
* @return void
*/
- function __construct()
+ public function __construct()
{
parent::__construct();
}
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function connect($dsn, $persistent = false)
+ public function connect($dsn, $persistent = false)
{
if (!PEAR::loadExtension('sybase') &&
- !PEAR::loadExtension('sybase_ct'))
- {
+ !PEAR::loadExtension('sybase_ct')) {
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
}
$connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect';
if ($dsn['username']) {
- $this->connection = @$connect_function($dsn['hostspec'],
- $dsn['username'],
- $dsn['password'],
- $dsn['charset'],
- $dsn['appname']);
+ $this->connection = @$connect_function(
+ $dsn['hostspec'],
+ $dsn['username'],
+ $dsn['password'],
+ $dsn['charset'],
+ $dsn['appname']
+ );
} else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- 'The DSN did not contain a username.');
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ 'The DSN did not contain a username.'
+ );
}
if (!$this->connection) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED,
- null, null, null,
- @sybase_get_last_message());
+ return $this->raiseError(
+ DB_ERROR_CONNECT_FAILED,
+ null,
+ null,
+ null,
+ @sybase_get_last_message()
+ );
}
if ($dsn['database']) {
if (!@sybase_select_db($dsn['database'], $this->connection)) {
- return $this->raiseError(DB_ERROR_NODBSELECTED,
- null, null, null,
- @sybase_get_last_message());
+ return $this->raiseError(
+ DB_ERROR_NODBSELECTED,
+ null,
+ null,
+ null,
+ @sybase_get_last_message()
+ );
}
$this->_db = $dsn['database'];
}
*
* @return bool TRUE on success, FALSE on failure
*/
- function disconnect()
+ public function disconnect()
{
$ret = @sybase_close($this->connection);
$this->connection = null;
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
*/
- function simpleQuery($query)
+ public function simpleQuery($query)
{
$ismanip = $this->_checkManip($query);
$this->last_query = $query;
*
* @return true if a result is available otherwise return false
*/
- function nextResult($result)
+ public function nextResult($result)
{
return false;
}
*
* @see DB_result::fetchInto()
*/
- function fetchInto($result, &$arr, $fetchmode, $rownum = null)
+ public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
{
if ($rownum !== null) {
if (!@sybase_data_seek($result, $rownum)) {
*
* @see DB_result::free()
*/
- function freeResult($result)
+ public function freeResult($result)
{
return is_resource($result) ? sybase_free_result($result) : false;
}
*
* @see DB_result::numCols()
*/
- function numCols($result)
+ public function numCols($result)
{
$cols = @sybase_num_fields($result);
if (!$cols) {
*
* @see DB_result::numRows()
*/
- function numRows($result)
+ public function numRows($result)
{
$rows = @sybase_num_rows($result);
if ($rows === false) {
*
* @return int the number of rows. A DB_Error object on failure.
*/
- function affectedRows()
+ public function affectedRows()
{
if ($this->_last_query_manip) {
$result = @sybase_affected_rows($this->connection);
$result = 0;
}
return $result;
- }
+ }
// }}}
// {{{ nextId()
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_sybase::createSequence(), DB_sybase::dropSequence()
*/
- function nextId($seq_name, $ondemand = true)
+ public function nextId($seq_name, $ondemand = true)
{
$seqname = $this->getSequenceName($seq_name);
if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
$result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
$this->popErrorHandling();
if ($ondemand && DB::isError($result) &&
- ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
- {
+ ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE)) {
$repeat = 1;
$result = $this->createSequence($seq_name);
if (DB::isError($result)) {
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_sybase::nextID(), DB_sybase::dropSequence()
*/
- function createSequence($seq_name)
+ public function createSequence($seq_name)
{
return $this->query('CREATE TABLE '
. $this->getSequenceName($seq_name)
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_sybase::nextID(), DB_sybase::createSequence()
*/
- function dropSequence($seq_name)
+ public function dropSequence($seq_name)
{
return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
}
* @see DB_common::quoteSmart()
* @since Method available since release 1.7.8.
*/
- function quoteFloat($float) {
+ public function quoteFloat($float)
+ {
return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
}
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
- function autoCommit($onoff = false)
+ public function autoCommit($onoff = false)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function commit()
+ public function commit()
{
if ($this->transaction_opcount > 0) {
if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
- function rollback()
+ public function rollback()
{
if ($this->transaction_opcount > 0) {
if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
* @see DB_common::raiseError(),
* DB_sybase::errorNative(), DB_sybase::errorCode()
*/
- function sybaseRaiseError($errno = null)
+ public function sybaseRaiseError($errno = null)
{
$native = $this->errorNative();
if ($errno === null) {
*
* @return string the DBMS' error message
*/
- function errorNative()
+ public function errorNative()
{
return @sybase_get_last_message();
}
* @param string $errormsg error message returned from the database
* @return integer an error number from a DB error constant
*/
- function errorCode($errormsg)
+ public function errorCode($errormsg)
{
static $error_regexps;
* @see DB_common::tableInfo()
* @since Method available since Release 1.6.0
*/
- function tableInfo($result, $mode = null)
+ public function tableInfo($result, $mode = null)
{
if (is_string($result)) {
/*
if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
}
- $id = @sybase_query("SELECT * FROM $result WHERE 1=0",
- $this->connection);
+ $id = @sybase_query(
+ "SELECT * FROM $result WHERE 1=0",
+ $this->connection
+ );
$got_string = true;
} elseif (isset($result->result)) {
/*
);
if ($res[$i]['table']) {
$res[$i]['flags'] = $this->_sybase_field_flags(
- $res[$i]['table'], $res[$i]['name']);
+ $res[$i]['table'],
+ $res[$i]['name']
+ );
}
if ($mode & DB_TABLEINFO_ORDER) {
$res['order'][$res[$i]['name']] = $i;
*
* @access private
*/
- function _sybase_field_flags($table, $column)
+ public function _sybase_field_flags($table, $column)
{
static $tableName = null;
static $flags = array();
}
sybase_free_result($res);
-
}
if (array_key_exists($column, $flags)) {
*
* @access private
*/
- function _add_flag(&$array, $value)
+ public function _add_flag(&$array, $value)
{
if (!is_array($array)) {
$array = array($value);
* @access protected
* @see DB_common::getListOf()
*/
- function getSpecialQuery($type)
+ public function getSpecialQuery($type)
{
switch ($type) {
case 'tables':
}
// }}}
-
}
/*
* c-basic-offset: 4
* End:
*/
-
-?>