PageRenderTime 53ms CodeModel.GetById 23ms app.highlight 22ms RepoModel.GetById 2ms app.codeStats 0ms

/halogy/database/DB_driver.php

https://bitbucket.org/haloweb/halogy-1.0/
PHP | 1366 lines | 698 code | 198 blank | 470 comment | 122 complexity | 90509a270df63b196ce10c1706cf9177 MD5 | raw file
   1<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   2/**
   3 * CodeIgniter
   4 *
   5 * An open source application development framework for PHP 4.3.2 or newer
   6 *
   7 * @package		CodeIgniter
   8 * @author		ExpressionEngine Dev Team
   9 * @copyright	Copyright (c) 2008 - 2009, EllisLab, Inc.
  10 * @license		http://codeigniter.com/user_guide/license.html
  11 * @link		http://codeigniter.com
  12 * @since		Version 1.0
  13 * @filesource
  14 */
  15
  16// ------------------------------------------------------------------------
  17
  18/**
  19 * Database Driver Class
  20 *
  21 * This is the platform-independent base DB implementation class.
  22 * This class will not be called directly. Rather, the adapter
  23 * class for the specific database will extend and instantiate it.
  24 *
  25 * @package		CodeIgniter
  26 * @subpackage	Drivers
  27 * @category	Database
  28 * @author		ExpressionEngine Dev Team
  29 * @link		http://codeigniter.com/user_guide/database/
  30 */
  31class CI_DB_driver {
  32
  33	var $username;
  34	var $password;
  35	var $hostname;
  36	var $database;
  37	var $dbdriver		= 'mysql';
  38	var $dbprefix		= '';
  39	var $char_set		= 'utf8';
  40	var $dbcollat		= 'utf8_general_ci';
  41	var $autoinit		= TRUE; // Whether to automatically initialize the DB
  42	var $swap_pre		= '';
  43	var $port			= '';
  44	var $pconnect		= FALSE;
  45	var $conn_id		= FALSE;
  46	var $result_id		= FALSE;
  47	var $db_debug		= FALSE;
  48	var $benchmark		= 0;
  49	var $query_count	= 0;
  50	var $bind_marker	= '?';
  51	var $save_queries	= TRUE;
  52	var $queries		= array();
  53	var $query_times	= array();
  54	var $data_cache		= array();
  55	var $trans_enabled	= TRUE;
  56	var $trans_strict	= TRUE;
  57	var $_trans_depth	= 0;
  58	var $_trans_status	= TRUE; // Used with transactions to determine if a rollback should occur
  59	var $cache_on		= FALSE;
  60	var $cachedir		= '';
  61	var $cache_autodel	= FALSE;
  62	var $CACHE; // The cache class object
  63
  64	// Private variables
  65	var $_protect_identifiers	= TRUE;
  66	var $_reserved_identifiers	= array('*'); // Identifiers that should NOT be escaped
  67
  68	// These are use with Oracle
  69	var $stmt_id;
  70	var $curs_id;
  71	var $limit_used;
  72
  73
  74	
  75	/**
  76	 * Constructor.  Accepts one parameter containing the database
  77	 * connection settings.
  78	 *
  79	 * @param array
  80	 */	
  81	function CI_DB_driver($params)
  82	{
  83		if (is_array($params))
  84		{
  85			foreach ($params as $key => $val)
  86			{
  87				$this->$key = $val;
  88			}
  89		}
  90
  91		log_message('debug', 'Database Driver Class Initialized');
  92	}
  93	
  94	// --------------------------------------------------------------------
  95
  96	/**
  97	 * Initialize Database Settings
  98	 *
  99	 * @access	private Called by the constructor
 100	 * @param	mixed
 101	 * @return	void
 102	 */	
 103	function initialize()
 104	{
 105		// If an existing connection resource is available
 106		// there is no need to connect and select the database
 107		if (is_resource($this->conn_id) OR is_object($this->conn_id))
 108		{
 109			return TRUE;
 110		}
 111	
 112		// ----------------------------------------------------------------
 113		
 114		// Connect to the database and set the connection ID
 115		$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
 116
 117		// No connection resource?  Throw an error
 118		if ( ! $this->conn_id)
 119		{
 120			log_message('error', 'Unable to connect to the database');
 121			
 122			if ($this->db_debug)
 123			{
 124				$this->display_error('db_unable_to_connect');
 125			}
 126			return FALSE;
 127		}
 128
 129		// ----------------------------------------------------------------
 130
 131		// Select the DB... assuming a database name is specified in the config file
 132		if ($this->database != '')
 133		{
 134			if ( ! $this->db_select())
 135			{
 136				log_message('error', 'Unable to select database: '.$this->database);
 137			
 138				if ($this->db_debug)
 139				{
 140					$this->display_error('db_unable_to_select', $this->database);
 141				}
 142				return FALSE;			
 143			}
 144			else
 145			{
 146				// We've selected the DB. Now we set the character set
 147				if ( ! $this->db_set_charset($this->char_set, $this->dbcollat))
 148				{
 149					return FALSE;
 150				}
 151		
 152				return TRUE;
 153			}
 154		}
 155
 156		return TRUE;
 157	}
 158		
 159	// --------------------------------------------------------------------
 160
 161	/**
 162	 * Set client character set
 163	 *
 164	 * @access	public
 165	 * @param	string
 166	 * @param	string
 167	 * @return	resource
 168	 */
 169	function db_set_charset($charset, $collation)
 170	{
 171		if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat))
 172		{
 173			log_message('error', 'Unable to set database connection charset: '.$this->char_set);
 174		
 175			if ($this->db_debug)
 176			{
 177				$this->display_error('db_unable_to_set_charset', $this->char_set);
 178			}
 179			
 180			return FALSE;
 181		}
 182		
 183		return TRUE;
 184	}
 185	
 186	// --------------------------------------------------------------------
 187
 188	/**
 189	 * The name of the platform in use (mysql, mssql, etc...)
 190	 *
 191	 * @access	public
 192	 * @return	string		
 193	 */	
 194	function platform()
 195	{
 196		return $this->dbdriver;
 197	}
 198
 199	// --------------------------------------------------------------------
 200
 201	/**
 202	 * Database Version Number.  Returns a string containing the
 203	 * version of the database being used
 204	 *
 205	 * @access	public
 206	 * @return	string	
 207	 */	
 208	function version()
 209	{
 210		if (FALSE === ($sql = $this->_version()))
 211		{
 212			if ($this->db_debug)
 213			{
 214				return $this->display_error('db_unsupported_function');
 215			}
 216			return FALSE;
 217		}
 218		
 219		if ($this->dbdriver == 'oci8')
 220		{
 221			return $sql;
 222		}
 223	
 224		$query = $this->query($sql);
 225		return $query->row('ver');
 226	}
 227	
 228	// --------------------------------------------------------------------
 229
 230	/**
 231	 * Execute the query
 232	 *
 233	 * Accepts an SQL string as input and returns a result object upon
 234	 * successful execution of a "read" type query.  Returns boolean TRUE
 235	 * upon successful execution of a "write" type query. Returns boolean
 236	 * FALSE upon failure, and if the $db_debug variable is set to TRUE
 237	 * will raise an error.
 238	 *
 239	 * @access	public
 240	 * @param	string	An SQL query string
 241	 * @param	array	An array of binding data
 242	 * @return	mixed		
 243	 */	
 244	function query($sql, $binds = FALSE, $return_object = TRUE)
 245	{
 246		if ($sql == '')
 247		{
 248			if ($this->db_debug)
 249			{
 250				log_message('error', 'Invalid query: '.$sql);
 251				return $this->display_error('db_invalid_query');
 252			}
 253			return FALSE;
 254		}
 255
 256		// Verify table prefix and replace if necessary
 257		if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
 258		{			
 259			$sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
 260		}
 261		
 262		// Is query caching enabled?  If the query is a "read type"
 263		// we will load the caching class and return the previously
 264		// cached query if it exists
 265		if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
 266		{
 267			if ($this->_cache_init())
 268			{
 269				$this->load_rdriver();
 270				if (FALSE !== ($cache = $this->CACHE->read($sql)))
 271				{
 272					return $cache;
 273				}
 274			}
 275		}
 276		
 277		// Compile binds if needed
 278		if ($binds !== FALSE)
 279		{
 280			$sql = $this->compile_binds($sql, $binds);
 281		}
 282
 283		// Save the  query for debugging
 284		if ($this->save_queries == TRUE)
 285		{
 286			$this->queries[] = $sql;
 287		}
 288		
 289		// Start the Query Timer
 290		$time_start = list($sm, $ss) = explode(' ', microtime());
 291	
 292		// Run the Query
 293		if (FALSE === ($this->result_id = $this->simple_query($sql)))
 294		{
 295			if ($this->save_queries == TRUE)
 296			{
 297				$this->query_times[] = 0;
 298			}
 299		
 300			// This will trigger a rollback if transactions are being used
 301			$this->_trans_status = FALSE;
 302
 303			if ($this->db_debug)
 304			{
 305				// grab the error number and message now, as we might run some
 306				// additional queries before displaying the error
 307				$error_no = $this->_error_number();
 308				$error_msg = $this->_error_message();
 309				
 310				// We call this function in order to roll-back queries
 311				// if transactions are enabled.  If we don't call this here
 312				// the error message will trigger an exit, causing the 
 313				// transactions to remain in limbo.
 314				$this->trans_complete();
 315
 316				// Log and display errors
 317				log_message('error', 'Query error: '.$error_msg);
 318				return $this->display_error(
 319										array(
 320												'Error Number: '.$error_no,
 321												$error_msg,
 322												$sql
 323											)
 324										);
 325			}
 326		
 327			return FALSE;
 328		}
 329		
 330		// Stop and aggregate the query time results
 331		$time_end = list($em, $es) = explode(' ', microtime());
 332		$this->benchmark += ($em + $es) - ($sm + $ss);
 333
 334		if ($this->save_queries == TRUE)
 335		{
 336			$this->query_times[] = ($em + $es) - ($sm + $ss);
 337		}
 338		
 339		// Increment the query counter
 340		$this->query_count++;
 341		
 342		// Was the query a "write" type?
 343		// If so we'll simply return true
 344		if ($this->is_write_type($sql) === TRUE)
 345		{
 346			// If caching is enabled we'll auto-cleanup any
 347			// existing files related to this particular URI
 348			if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
 349			{
 350				$this->CACHE->delete();
 351			}
 352		
 353			return TRUE;
 354		}
 355		
 356		// Return TRUE if we don't need to create a result object
 357		// Currently only the Oracle driver uses this when stored
 358		// procedures are used
 359		if ($return_object !== TRUE)
 360		{
 361			return TRUE;
 362		}
 363	
 364		// Load and instantiate the result driver	
 365		
 366		$driver 		= $this->load_rdriver();
 367		$RES 			= new $driver();
 368		$RES->conn_id	= $this->conn_id;
 369		$RES->result_id	= $this->result_id;
 370
 371		if ($this->dbdriver == 'oci8')
 372		{
 373			$RES->stmt_id		= $this->stmt_id;
 374			$RES->curs_id		= NULL;
 375			$RES->limit_used	= $this->limit_used;
 376			$this->stmt_id		= FALSE;
 377		}
 378		
 379		// oci8 vars must be set before calling this
 380		$RES->num_rows	= $RES->num_rows();
 381				
 382		// Is query caching enabled?  If so, we'll serialize the
 383		// result object and save it to a cache file.
 384		if ($this->cache_on == TRUE AND $this->_cache_init())
 385		{
 386			// We'll create a new instance of the result object
 387			// only without the platform specific driver since
 388			// we can't use it with cached data (the query result
 389			// resource ID won't be any good once we've cached the
 390			// result object, so we'll have to compile the data
 391			// and save it)
 392			$CR = new CI_DB_result();
 393			$CR->num_rows 		= $RES->num_rows();
 394			$CR->result_object	= $RES->result_object();
 395			$CR->result_array	= $RES->result_array();
 396			
 397			// Reset these since cached objects can not utilize resource IDs.
 398			$CR->conn_id		= NULL;
 399			$CR->result_id		= NULL;
 400
 401			$this->CACHE->write($sql, $CR);
 402		}
 403		
 404		return $RES;
 405	}
 406
 407	// --------------------------------------------------------------------
 408
 409	/**
 410	 * Load the result drivers
 411	 *
 412	 * @access	public
 413	 * @return	string 	the name of the result class		
 414	 */		
 415	function load_rdriver()
 416	{
 417		$driver = 'CI_DB_'.$this->dbdriver.'_result';
 418
 419		if ( ! class_exists($driver))
 420		{
 421			include_once(BASEPATH.'database/DB_result'.EXT);
 422			include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result'.EXT);
 423		}
 424		
 425		return $driver;
 426	}
 427	
 428	// --------------------------------------------------------------------
 429
 430	/**
 431	 * Simple Query
 432	 * This is a simplified version of the query() function.  Internally
 433	 * we only use it when running transaction commands since they do
 434	 * not require all the features of the main query() function.
 435	 *
 436	 * @access	public
 437	 * @param	string	the sql query
 438	 * @return	mixed		
 439	 */	
 440	function simple_query($sql)
 441	{
 442		if ( ! $this->conn_id)
 443		{
 444			$this->initialize();
 445		}
 446
 447		return $this->_execute($sql);
 448	}
 449	
 450	// --------------------------------------------------------------------
 451
 452	/**
 453	 * Disable Transactions
 454	 * This permits transactions to be disabled at run-time.
 455	 *
 456	 * @access	public
 457	 * @return	void		
 458	 */	
 459	function trans_off()
 460	{
 461		$this->trans_enabled = FALSE;
 462	}
 463
 464	// --------------------------------------------------------------------
 465
 466	/**
 467	 * Enable/disable Transaction Strict Mode
 468	 * When strict mode is enabled, if you are running multiple groups of
 469	 * transactions, if one group fails all groups will be rolled back.
 470	 * If strict mode is disabled, each group is treated autonomously, meaning
 471	 * a failure of one group will not affect any others
 472	 *
 473	 * @access	public
 474	 * @return	void		
 475	 */	
 476	function trans_strict($mode = TRUE)
 477	{
 478		$this->trans_strict = is_bool($mode) ? $mode : TRUE;
 479	}
 480	
 481	// --------------------------------------------------------------------
 482
 483	/**
 484	 * Start Transaction
 485	 *
 486	 * @access	public
 487	 * @return	void		
 488	 */	
 489	function trans_start($test_mode = FALSE)
 490	{	
 491		if ( ! $this->trans_enabled)
 492		{
 493			return FALSE;
 494		}
 495
 496		// When transactions are nested we only begin/commit/rollback the outermost ones
 497		if ($this->_trans_depth > 0)
 498		{
 499			$this->_trans_depth += 1;
 500			return;
 501		}
 502		
 503		$this->trans_begin($test_mode);
 504	}
 505
 506	// --------------------------------------------------------------------
 507
 508	/**
 509	 * Complete Transaction
 510	 *
 511	 * @access	public
 512	 * @return	bool		
 513	 */	
 514	function trans_complete()
 515	{
 516		if ( ! $this->trans_enabled)
 517		{
 518			return FALSE;
 519		}
 520	
 521		// When transactions are nested we only begin/commit/rollback the outermost ones
 522		if ($this->_trans_depth > 1)
 523		{
 524			$this->_trans_depth -= 1;
 525			return TRUE;
 526		}
 527	
 528		// The query() function will set this flag to FALSE in the event that a query failed
 529		if ($this->_trans_status === FALSE)
 530		{
 531			$this->trans_rollback();
 532			
 533			// If we are NOT running in strict mode, we will reset
 534			// the _trans_status flag so that subsequent groups of transactions
 535			// will be permitted.
 536			if ($this->trans_strict === FALSE)
 537			{
 538				$this->_trans_status = TRUE;
 539			}
 540
 541			log_message('debug', 'DB Transaction Failure');
 542			return FALSE;
 543		}
 544		
 545		$this->trans_commit();
 546		return TRUE;
 547	}
 548
 549	// --------------------------------------------------------------------
 550
 551	/**
 552	 * Lets you retrieve the transaction flag to determine if it has failed
 553	 *
 554	 * @access	public
 555	 * @return	bool		
 556	 */	
 557	function trans_status()
 558	{
 559		return $this->_trans_status;
 560	}
 561
 562	// --------------------------------------------------------------------
 563
 564	/**
 565	 * Compile Bindings
 566	 *
 567	 * @access	public
 568	 * @param	string	the sql statement
 569	 * @param	array	an array of bind data
 570	 * @return	string		
 571	 */	
 572	function compile_binds($sql, $binds)
 573	{
 574		if (strpos($sql, $this->bind_marker) === FALSE)
 575		{
 576			return $sql;
 577		}
 578		
 579		if ( ! is_array($binds))
 580		{
 581			$binds = array($binds);
 582		}
 583		
 584		// Get the sql segments around the bind markers
 585		$segments = explode($this->bind_marker, $sql);
 586
 587		// The count of bind should be 1 less then the count of segments
 588		// If there are more bind arguments trim it down
 589		if (count($binds) >= count($segments)) {
 590			$binds = array_slice($binds, 0, count($segments)-1);
 591		}
 592
 593		// Construct the binded query
 594		$result = $segments[0];
 595		$i = 0;
 596		foreach ($binds as $bind)
 597		{
 598			$result .= $this->escape($bind);
 599			$result .= $segments[++$i];
 600		}
 601
 602		return $result;
 603	}
 604	
 605	// --------------------------------------------------------------------
 606
 607	/**
 608	 * Determines if a query is a "write" type.
 609	 *
 610	 * @access	public
 611	 * @param	string	An SQL query string
 612	 * @return	boolean		
 613	 */	
 614	function is_write_type($sql)
 615	{
 616		if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
 617		{
 618			return FALSE;
 619		}
 620		return TRUE;
 621	}
 622	
 623	// --------------------------------------------------------------------
 624
 625	/**
 626	 * Calculate the aggregate query elapsed time
 627	 *
 628	 * @access	public
 629	 * @param	integer	The number of decimal places
 630	 * @return	integer		
 631	 */	
 632	function elapsed_time($decimals = 6)
 633	{
 634		return number_format($this->benchmark, $decimals);
 635	}
 636	
 637	// --------------------------------------------------------------------
 638
 639	/**
 640	 * Returns the total number of queries
 641	 *
 642	 * @access	public
 643	 * @return	integer		
 644	 */	
 645	function total_queries()
 646	{
 647		return $this->query_count;
 648	}
 649	
 650	// --------------------------------------------------------------------
 651
 652	/**
 653	 * Returns the last query that was executed
 654	 *
 655	 * @access	public
 656	 * @return	void		
 657	 */	
 658	function last_query()
 659	{
 660		return end($this->queries);
 661	}
 662
 663	// --------------------------------------------------------------------
 664
 665	/**
 666	 * "Smart" Escape String
 667	 *
 668	 * Escapes data based on type
 669	 * Sets boolean and null types
 670	 *
 671	 * @access	public
 672	 * @param	string
 673	 * @return	mixed		
 674	 */	
 675	function escape($str)
 676	{
 677		if (is_string($str))
 678		{
 679			$str = "'".$this->escape_str($str)."'";
 680		}
 681		elseif (is_bool($str))
 682		{
 683			$str = ($str === FALSE) ? 0 : 1;
 684		}
 685		elseif (is_null($str))
 686		{
 687			$str = 'NULL';
 688		}
 689
 690		return $str;
 691	}
 692
 693	// --------------------------------------------------------------------
 694	
 695	/**
 696	 * Escape LIKE String
 697	 *
 698	 * Calls the individual driver for platform
 699	 * specific escaping for LIKE conditions
 700	 * 
 701	 * @access	public
 702	 * @param	string
 703	 * @return	mixed
 704	 */
 705    function escape_like_str($str)    
 706    {    
 707    	return $this->escape_str($str, TRUE);
 708	}
 709
 710	// --------------------------------------------------------------------
 711	
 712	/**
 713	 * Primary
 714	 *
 715	 * Retrieves the primary key.  It assumes that the row in the first
 716	 * position is the primary key
 717	 *
 718	 * @access	public
 719	 * @param	string	the table name
 720	 * @return	string		
 721	 */	
 722	function primary($table = '')
 723	{	
 724		$fields = $this->list_fields($table);
 725		
 726		if ( ! is_array($fields))
 727		{
 728			return FALSE;
 729		}
 730
 731		return current($fields);
 732	}
 733
 734	// --------------------------------------------------------------------
 735
 736	/**
 737	 * Returns an array of table names
 738	 *
 739	 * @access	public
 740	 * @return	array		
 741	 */	
 742	function list_tables($constrain_by_prefix = FALSE)
 743	{
 744		// Is there a cached result?
 745		if (isset($this->data_cache['table_names']))
 746		{
 747			return $this->data_cache['table_names'];
 748		}
 749	
 750		if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
 751		{
 752			if ($this->db_debug)
 753			{
 754				return $this->display_error('db_unsupported_function');
 755			}
 756			return FALSE;
 757		}
 758
 759		$retval = array();
 760		$query = $this->query($sql);
 761		
 762		if ($query->num_rows() > 0)
 763		{
 764			foreach($query->result_array() as $row)
 765			{
 766				if (isset($row['TABLE_NAME']))
 767				{
 768					$retval[] = $row['TABLE_NAME'];
 769				}
 770				else
 771				{
 772					$retval[] = array_shift($row);
 773				}
 774			}
 775		}
 776
 777		$this->data_cache['table_names'] = $retval;
 778		return $this->data_cache['table_names'];
 779	}
 780	
 781	// --------------------------------------------------------------------
 782
 783	/**
 784	 * Determine if a particular table exists
 785	 * @access	public
 786	 * @return	boolean
 787	 */
 788	function table_exists($table_name)
 789	{	
 790		return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE;
 791	}
 792	
 793	// --------------------------------------------------------------------
 794
 795	/**
 796	 * Fetch MySQL Field Names
 797	 *
 798	 * @access	public
 799	 * @param	string	the table name
 800	 * @return	array		
 801	 */
 802	function list_fields($table = '')
 803	{
 804		// Is there a cached result?
 805		if (isset($this->data_cache['field_names'][$table]))
 806		{
 807			return $this->data_cache['field_names'][$table];
 808		}
 809	
 810		if ($table == '')
 811		{
 812			if ($this->db_debug)
 813			{
 814				return $this->display_error('db_field_param_missing');
 815			}
 816			return FALSE;
 817		}
 818		
 819		if (FALSE === ($sql = $this->_list_columns($this->_protect_identifiers($table, TRUE, NULL, FALSE))))
 820		{
 821			if ($this->db_debug)
 822			{
 823				return $this->display_error('db_unsupported_function');
 824			}
 825			return FALSE;
 826		}
 827		
 828		$query = $this->query($sql);
 829		
 830		$retval = array();
 831		foreach($query->result_array() as $row)
 832		{
 833			if (isset($row['COLUMN_NAME']))
 834			{
 835				$retval[] = $row['COLUMN_NAME'];
 836			}
 837			else
 838			{
 839				$retval[] = current($row);
 840			}		
 841		}
 842		
 843		$this->data_cache['field_names'][$table] = $retval;
 844		return $this->data_cache['field_names'][$table];
 845	}
 846
 847	// --------------------------------------------------------------------
 848
 849	/**
 850	 * Determine if a particular field exists
 851	 * @access	public
 852	 * @param	string
 853	 * @param	string
 854	 * @return	boolean
 855	 */
 856	function field_exists($field_name, $table_name)
 857	{	
 858		return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
 859	}
 860	
 861	// --------------------------------------------------------------------
 862
 863	/**
 864	 * Returns an object with field data
 865	 *
 866	 * @access	public
 867	 * @param	string	the table name
 868	 * @return	object		
 869	 */	
 870	function field_data($table = '')
 871	{
 872		if ($table == '')
 873		{
 874			if ($this->db_debug)
 875			{
 876				return $this->display_error('db_field_param_missing');
 877			}
 878			return FALSE;
 879		}
 880		
 881		$query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE)));
 882
 883		return $query->field_data();
 884	}	
 885
 886	// --------------------------------------------------------------------
 887	
 888	/**
 889	 * Generate an insert string
 890	 *
 891	 * @access	public
 892	 * @param	string	the table upon which the query will be performed
 893	 * @param	array	an associative array data of key/values
 894	 * @return	string		
 895	 */	
 896	function insert_string($table, $data)
 897	{
 898		$fields = array();
 899		$values = array();
 900		
 901		foreach($data as $key => $val)
 902		{
 903			$fields[] = $this->_escape_identifiers($key);
 904			$values[] = $this->escape($val);
 905		}
 906				
 907		return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
 908	}	
 909	
 910	// --------------------------------------------------------------------
 911
 912	/**
 913	 * Generate an update string
 914	 *
 915	 * @access	public
 916	 * @param	string	the table upon which the query will be performed
 917	 * @param	array	an associative array data of key/values
 918	 * @param	mixed	the "where" statement
 919	 * @return	string		
 920	 */	
 921	function update_string($table, $data, $where)
 922	{
 923		if ($where == '')
 924		{
 925			return false;
 926		}
 927					
 928		$fields = array();
 929		foreach($data as $key => $val)
 930		{
 931			$fields[$this->_protect_identifiers($key)] = $this->escape($val);
 932		}
 933
 934		if ( ! is_array($where))
 935		{
 936			$dest = array($where);
 937		}
 938		else
 939		{
 940			$dest = array();
 941			foreach ($where as $key => $val)
 942			{
 943				$prefix = (count($dest) == 0) ? '' : ' AND ';
 944	
 945				if ($val !== '')
 946				{
 947					if ( ! $this->_has_operator($key))
 948					{
 949						$key .= ' =';
 950					}
 951				
 952					$val = ' '.$this->escape($val);
 953				}
 954							
 955				$dest[] = $prefix.$key.$val;
 956			}
 957		}		
 958
 959		return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest);
 960	}	
 961
 962	// --------------------------------------------------------------------
 963
 964	/**
 965	 * Tests whether the string has an SQL operator
 966	 *
 967	 * @access	private
 968	 * @param	string
 969	 * @return	bool
 970	 */
 971	function _has_operator($str)
 972	{
 973		$str = trim($str);
 974		if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
 975		{
 976			return FALSE;
 977		}
 978
 979		return TRUE;
 980	}
 981
 982	// --------------------------------------------------------------------
 983
 984	/**
 985	 * Enables a native PHP function to be run, using a platform agnostic wrapper.
 986	 *
 987	 * @access	public
 988	 * @param	string	the function name
 989	 * @param	mixed	any parameters needed by the function
 990	 * @return	mixed		
 991	 */	
 992	function call_function($function)
 993	{
 994		$driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
 995	
 996		if (FALSE === strpos($driver, $function))
 997		{
 998			$function = $driver.$function;
 999		}
1000		
1001		if ( ! function_exists($function))
1002		{
1003			if ($this->db_debug)
1004			{
1005				return $this->display_error('db_unsupported_function');
1006			}
1007			return FALSE;
1008		}
1009		else
1010		{
1011			$args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
1012
1013			return call_user_func_array($function, $args);
1014		}
1015	}
1016
1017	// --------------------------------------------------------------------
1018
1019	/**
1020	 * Set Cache Directory Path
1021	 *
1022	 * @access	public
1023	 * @param	string	the path to the cache directory
1024	 * @return	void
1025	 */		
1026	function cache_set_path($path = '')
1027	{
1028		$this->cachedir = $path;
1029	}
1030
1031	// --------------------------------------------------------------------
1032
1033	/**
1034	 * Enable Query Caching
1035	 *
1036	 * @access	public
1037	 * @return	void
1038	 */		
1039	function cache_on()
1040	{
1041		$this->cache_on = TRUE;
1042		return TRUE;
1043	}
1044
1045	// --------------------------------------------------------------------
1046
1047	/**
1048	 * Disable Query Caching
1049	 *
1050	 * @access	public
1051	 * @return	void
1052	 */	
1053	function cache_off()
1054	{
1055		$this->cache_on = FALSE;
1056		return FALSE;
1057	}
1058	
1059
1060	// --------------------------------------------------------------------
1061
1062	/**
1063	 * Delete the cache files associated with a particular URI
1064	 *
1065	 * @access	public
1066	 * @return	void
1067	 */		
1068	function cache_delete($segment_one = '', $segment_two = '')
1069	{
1070		if ( ! $this->_cache_init())
1071		{
1072			return FALSE;
1073		}
1074		return $this->CACHE->delete($segment_one, $segment_two);
1075	}
1076
1077	// --------------------------------------------------------------------
1078
1079	/**
1080	 * Delete All cache files
1081	 *
1082	 * @access	public
1083	 * @return	void
1084	 */		
1085	function cache_delete_all()
1086	{
1087		if ( ! $this->_cache_init())
1088		{
1089			return FALSE;
1090		}
1091
1092		return $this->CACHE->delete_all();
1093	}
1094
1095	// --------------------------------------------------------------------
1096
1097	/**
1098	 * Initialize the Cache Class
1099	 *
1100	 * @access	private
1101	 * @return	void
1102	 */	
1103	function _cache_init()
1104	{
1105		if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
1106		{
1107			return TRUE;
1108		}
1109
1110		if ( ! class_exists('CI_DB_Cache'))
1111		{
1112			if ( ! @include(BASEPATH.'database/DB_cache'.EXT))
1113			{
1114				return $this->cache_off();
1115			}
1116		}
1117
1118		$this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
1119		return TRUE;
1120	}
1121
1122	// --------------------------------------------------------------------
1123
1124	/**
1125	 * Close DB Connection
1126	 *
1127	 * @access	public
1128	 * @return	void		
1129	 */	
1130	function close()
1131	{
1132		if (is_resource($this->conn_id) OR is_object($this->conn_id))
1133		{
1134			$this->_close($this->conn_id);
1135		}
1136		$this->conn_id = FALSE;
1137	}
1138	
1139	// --------------------------------------------------------------------
1140
1141	/**
1142	 * Display an error message
1143	 *
1144	 * @access	public
1145	 * @param	string	the error message
1146	 * @param	string	any "swap" values
1147	 * @param	boolean	whether to localize the message
1148	 * @return	string	sends the application/error_db.php template		
1149	 */	
1150	function display_error($error = '', $swap = '', $native = FALSE)
1151	{
1152		$LANG =& load_class('Language');
1153		$LANG->load('db');
1154
1155		$heading = $LANG->line('db_error_heading');
1156
1157		if ($native == TRUE)
1158		{
1159			$message = $error;
1160		}
1161		else
1162		{
1163			$message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
1164		}
1165		
1166		$error =& load_class('Exceptions');
1167		echo $error->show_error($heading, $message, 'error_db');
1168		exit;
1169	}
1170
1171	// --------------------------------------------------------------------
1172
1173	/**
1174	 * Protect Identifiers
1175	 *
1176	 * This function adds backticks if appropriate based on db type
1177	 *
1178	 * @access	private
1179	 * @param	mixed	the item to escape
1180	 * @return	mixed	the item with backticks
1181	 */
1182	function protect_identifiers($item, $prefix_single = FALSE)
1183	{
1184		return $this->_protect_identifiers($item, $prefix_single);
1185	}
1186
1187	// --------------------------------------------------------------------
1188
1189	/**
1190	 * Protect Identifiers
1191	 *
1192	 * This function is used extensively by the Active Record class, and by
1193	 * a couple functions in this class. 
1194	 * It takes a column or table name (optionally with an alias) and inserts
1195	 * the table prefix onto it.  Some logic is necessary in order to deal with
1196	 * column names that include the path.  Consider a query like this:
1197	 *
1198	 * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
1199	 *
1200	 * Or a query with aliasing:
1201	 *
1202	 * SELECT m.member_id, m.member_name FROM members AS m
1203	 *
1204	 * Since the column name can include up to four segments (host, DB, table, column)
1205	 * or also have an alias prefix, we need to do a bit of work to figure this out and
1206	 * insert the table prefix (if it exists) in the proper position, and escape only
1207	 * the correct identifiers.
1208	 *
1209	 * @access	private
1210	 * @param	string
1211	 * @param	bool
1212	 * @param	mixed
1213	 * @param	bool
1214	 * @return	string
1215	 */	
1216	function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
1217	{
1218		if ( ! is_bool($protect_identifiers))
1219		{
1220			$protect_identifiers = $this->_protect_identifiers;
1221		}
1222
1223		if (is_array($item))
1224		{
1225			$escaped_array = array();
1226
1227			foreach($item as $k => $v)
1228			{
1229				$escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
1230			}
1231
1232			return $escaped_array;
1233		}
1234
1235		// Convert tabs or multiple spaces into single spaces
1236		$item = preg_replace('/[\t ]+/', ' ', $item);
1237	
1238		// If the item has an alias declaration we remove it and set it aside.
1239		// Basically we remove everything to the right of the first space
1240		$alias = '';
1241		if (strpos($item, ' ') !== FALSE)
1242		{
1243			$alias = strstr($item, " ");
1244			$item = substr($item, 0, - strlen($alias));
1245		}
1246
1247		// This is basically a bug fix for queries that use MAX, MIN, etc.
1248		// If a parenthesis is found we know that we do not need to 
1249		// escape the data or add a prefix.  There's probably a more graceful
1250		// way to deal with this, but I'm not thinking of it -- Rick
1251		if (strpos($item, '(') !== FALSE)
1252		{
1253			return $item.$alias;
1254		}
1255
1256		// Break the string apart if it contains periods, then insert the table prefix
1257		// in the correct location, assuming the period doesn't indicate that we're dealing
1258		// with an alias. While we're at it, we will escape the components
1259		if (strpos($item, '.') !== FALSE)
1260		{
1261			$parts	= explode('.', $item);
1262			
1263			// Does the first segment of the exploded item match
1264			// one of the aliases previously identified?  If so,
1265			// we have nothing more to do other than escape the item
1266			if (in_array($parts[0], $this->ar_aliased_tables))
1267			{
1268				if ($protect_identifiers === TRUE)
1269				{
1270					foreach ($parts as $key => $val)
1271					{
1272						if ( ! in_array($val, $this->_reserved_identifiers))
1273						{
1274							$parts[$key] = $this->_escape_identifiers($val);
1275						}
1276					}
1277				
1278					$item = implode('.', $parts);
1279				}			
1280				return $item.$alias;
1281			}
1282			
1283			// Is there a table prefix defined in the config file?  If not, no need to do anything
1284			if ($this->dbprefix != '')
1285			{
1286				// We now add the table prefix based on some logic.
1287				// Do we have 4 segments (hostname.database.table.column)?
1288				// If so, we add the table prefix to the column name in the 3rd segment.
1289				if (isset($parts[3]))
1290				{
1291					$i = 2;
1292				}
1293				// Do we have 3 segments (database.table.column)?
1294				// If so, we add the table prefix to the column name in 2nd position
1295				elseif (isset($parts[2]))
1296				{
1297					$i = 1;
1298				}
1299				// Do we have 2 segments (table.column)?
1300				// If so, we add the table prefix to the column name in 1st segment
1301				else
1302				{
1303					$i = 0;
1304				}
1305				
1306				// This flag is set when the supplied $item does not contain a field name.
1307				// This can happen when this function is being called from a JOIN.
1308				if ($field_exists == FALSE)
1309				{
1310					$i++;
1311				}
1312
1313				// Verify table prefix and replace if necessary
1314				if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
1315				{
1316					$parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
1317				}
1318								
1319				// We only add the table prefix if it does not already exist
1320				if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
1321				{
1322					$parts[$i] = $this->dbprefix.$parts[$i];
1323				}
1324				
1325				// Put the parts back together
1326				$item = implode('.', $parts);
1327			}
1328			
1329			if ($protect_identifiers === TRUE)
1330			{
1331				$item = $this->_escape_identifiers($item);
1332			}
1333			
1334			return $item.$alias;
1335		}
1336
1337		// Is there a table prefix?  If not, no need to insert it
1338		if ($this->dbprefix != '')
1339		{
1340			// Verify table prefix and replace if necessary
1341			if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
1342			{
1343				$item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
1344			}
1345
1346			// Do we prefix an item with no segments?
1347			if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
1348			{
1349				$item = $this->dbprefix.$item;
1350			}		
1351		}
1352
1353		if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
1354		{
1355			$item = $this->_escape_identifiers($item);
1356		}
1357		
1358		return $item.$alias;
1359	}
1360
1361
1362}
1363
1364
1365/* End of file DB_driver.php */
1366/* Location: ./system/database/DB_driver.php */