/system/database/drivers/mysql/mysql_driver.php MYSQL数据库配置器类

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * MySQL Database Adapter Class
 * 
 * mysql 数据库的适配器类
 * 
 * Note: _DB is an extender class that the app controller
 * creates dynamically based on whether the active record
 * class is being used or not.
 * 
 * 注:_DB是一个扩展类应用控制器
 * 创建动态的基础上是否活动记录类正在使用与否。

 * @package		CodeIgniter
 * @subpackage	Drivers
 * @category	Database
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/database/
 */
class CI_DB_mysql_driver extends CI_DB {

	var $dbdriver = 'mysql';  //数据库类型
	

	// The character used for escaping 用于转义字符
	var	$_escape_char = '`'; 

	// clause and character used for LIKE escape sequences - not used in MySQL
	// 在MySQL中使用条款和字符用于LIKE转义序列 -
	var $_like_escape_str = '';
	var $_like_escape_chr = '';

	/**
	 * Whether to use the MySQL "delete hack" which allows the number
	 * of affected rows to be shown. Uses a preg_replace when enabled,
	 * adding a bit more processing to all queries.
	 * *是否使用MySQL的“删除”,它允许黑客的数量
     * 受影响的行显示。 preg_replace函数使用一个启用时,
     * 添加更多一点的处理所有的查询。
	 */
	var $delete_hack = TRUE;

	/**
	 * The syntax to count rows is slightly different across different
	 * database engines, so this string appears in each driver and is
	 * used for the count_all() and count_all_results() functions.
	 * 在不同的数行的语法略有不同
	 * 数据库引擎,所以这个字符串出现在每个驱动器和
	 * 用于count_all()和count_all_results()函数。
	 *
	 */
	var $_count_string = 'SELECT COUNT(*) AS ';
	var $_random_keyword = ' RAND()'; // database specific random keyword 数据库特定的随机关键字

	// whether SET NAMES must be used to set the character set
	// 是否SET名称必须使用设置字符集
	var $use_set_names;
	
	/**
	 * Non-persistent database connection
	 * 非持久性数据库连接
	 * @access	private called by the base class 私人称为基类
	 * @return	resource 返回资源
	 */
	function db_connect()
	{
		//发果接口不为空
		if ($this->port != '')
		{
			//拼接到hostname后面
			$this->hostname .= ':'.$this->port;
		}
        //返回一个数据库链接资源
		return @mysql_connect($this->hostname, $this->username, $this->password, TRUE);
	}

	// --------------------------------------------------------------------

	/**
	 * Persistent database connection
	 * 持久数据库连接
	 * @access	private called by the base class
	 * @return	resource
	 */
	function db_pconnect()
	{
		if ($this->port != '')
		{
			$this->hostname .= ':'.$this->port;
		}

		return @mysql_pconnect($this->hostname, $this->username, $this->password);
	}

	// --------------------------------------------------------------------

	/**
	 * Reconnect
	 * 重新连接
	 * 
	 * Keep / reestablish the db connection if no queries have been
	 * sent for a length of time exceeding the server's idle timeout
	 * 保持/重新建立数据库连接,如果没有查询
     * 发送的时间长度超过服务器的空闲超时
	 * @access	public
	 * @return	void
	 */
	function reconnect()
	{
		//mysql_ping($this->conn_id) === false 
		//mysql_ping 检查与服务端的连接是否正常检查与服务端的连接是否正常。连接断开时,如果自动重新连接功能未被禁用,则尝试重新连接服务器。该函数可被客户端用来检测闲置许久以后,与服务端的连接是否关闭,如有需要,则重新连接。
		if (mysql_ping($this->conn_id) === FALSE) //如果链接已经也断开
		{
			$this->conn_id = FALSE;  //将链接资源设置为false
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Select the database
	 * 选择数据库
	 * 
	 * @access	private called by the base class
	 * @return	resource
	 */
	function db_select()
	{
		return @mysql_select_db($this->database, $this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Set client character set
	 * 设置客户端的字符编码
	 * 
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	resource
	 */
	function db_set_charset($charset, $collation)
	{
		
		//如果没有设置字符
		if ( ! isset($this->use_set_names))
		{
			// mysql_set_charset() requires PHP >= 5.2.3 and MySQL >= 5.0.7, use SET NAMES as fallback
			// 在指定的php版本和mysql版本才能设置mysql_set_charset()函数
			$this->use_set_names = (version_compare(PHP_VERSION, '5.2.3', '>=') && version_compare(mysql_get_server_info(), '5.0.7', '>=')) ? FALSE : TRUE;
		}

		if ($this->use_set_names === TRUE)
		{
			//合适的版本,设置 set names
			return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id);
		}
		else
		{
			return @mysql_set_charset($charset, $this->conn_id);
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Version number query string
	 * 取得版本信息
	 * @access	public
	 * @return	string
	 */
	function _version()
	{
		return "SELECT version() AS ver";
	}

	// --------------------------------------------------------------------

	/**
	 * Execute the query
	 * 执行查询
	 * 
	 * @access	private called by the base class
	 * @param	string	an SQL query
	 * @return	resource
	 */
	function _execute($sql)
	{
		$sql = $this->_prep_query($sql);
		return @mysql_query($sql, $this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Prep the query
	 * 准备查询
	 * 
	 * If needed, each database adapter can prep the query string
	 * 如果需要,每个数据库适配器可以预先准备的查询字符串
	 * 
	 * @access	private called by execute()
	 * @param	string	an SQL query
	 * @return	string
	 */
	function _prep_query($sql)
	{
		// "DELETE FROM TABLE" returns 0 affected rows This hack modifies
		// the query so that it returns the number of affected rows
		// “DELETE FROM表”,返回受影响的行黑客修改
        // 查询,以便它返回受影响的行数
        
		// delete hack=破解
		if ($this->delete_hack === TRUE)
		{
			//如果字符串是为什 delete + FROM 一些字符串
			if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
			{
				//替换为delete from 1 where 1=1
				$sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
			}
		}

		return $sql;
	}

	// --------------------------------------------------------------------

	/**
	 * Begin Transaction
	 * 开始交易
	 * 
	 * @access	public
	 * @return	bool
	 */
	function trans_begin($test_mode = FALSE)
	{
		
		if ( ! $this->trans_enabled)
		{
			return TRUE;
		}

		// When transactions are nested we only begin/commit/rollback the outermost ones
		// 当事务被嵌套,我们才开始/提交/回滚最外层的
		if ($this->_trans_depth > 0)
		{
			return TRUE;
		}

		// Reset the transaction failure flag.
		// If the $test_mode flag is set to TRUE transactions will be rolled back
		// even if the queries produce a successful result.
		// 复位的交易失败标志。
        // 如果$ TEST_MODE标志设置为TRUE交易将回滚
        // 即使查询产生一个成功的结果。

		$this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;

		//开始事务处理
		//set AUTOCOMMIT=0 禁止自动提交
		$this->simple_query('SET AUTOCOMMIT=0');
		$this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK 也可以开始或开始工作
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Commit Transaction
	 * commit 事务
	 * 
	 * @access	public
	 * @return	bool
	 */
	function trans_commit()
	{
		if ( ! $this->trans_enabled)
		{
			return TRUE;
		}

		// When transactions are nested we only begin/commit/rollback the outermost ones
		// 当事务被嵌套,我们才开始/提交/回滚最外层的
		if ($this->_trans_depth > 0)
		{
			return TRUE;
		}
         
		//COMMIT 确定一个事务
		$this->simple_query('COMMIT');
		//SET AUTOCOMMIT=1 开启自动提交
		$this->simple_query('SET AUTOCOMMIT=1');
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Rollback Transaction
	 * 回滚事务
	 * 
	 * @access	public
	 * @return	bool
	 */
	function trans_rollback()
	{
		if ( ! $this->trans_enabled)
		{
			return TRUE;
		}

		// When transactions are nested we only begin/commit/rollback the outermost ones
		if ($this->_trans_depth > 0)
		{
			return TRUE;
		}
        //判断当前操作失败时回滚
        //ROLLBACK 判断当前操作失败时回滚
        
		$this->simple_query('ROLLBACK');
		$this->simple_query('SET AUTOCOMMIT=1');
		//set AUTOCOMMIT =1; 开启自动提交
		
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Escape String
	 * 转义字符串
	 * @access	public
	 * @param	string
	 * @param	bool	whether or not the string will be used in a LIKE condition
	 * @return	string  是否该字符串将被用于在LIKE条件
	 */
	function escape_str($str, $like = FALSE)
	{
		//如果是数组 循环进行递归操作
		if (is_array($str))
		{
			foreach ($str as $key => $val)
	   		{
				$str[$key] = $this->escape_str($val, $like);
	   		}

	   		return $str;
	   	}

	   	//判断是存存在mysql_real_escape_string函数
	   	
	   	//mysql_real_escape_string() 函数转义sql语句中使用的字符串的特殊字符	   	
	   	/*
		下列字符受影响:
		\x00
		\n
		\r
		\
		'
		"
		\x1a
		如果成功,则该函数返回被转义的字符串。如果失败,则返回 false。
	   	 * */	   	
		if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id))
		{
			$str = mysql_real_escape_string($str, $this->conn_id);
		}
		
		//mysql_escape_string() PHP 4 >= 4.0.3, PHP 5, 注意:在PHP5.3中已经弃用这种方法,不推荐使用
		elseif (function_exists('mysql_escape_string'))
		{
			$str = mysql_escape_string($str);
		}
		else
		{
			$str = addslashes($str); //直接用addslashes操作
		}

		// escape LIKE condition wildcards
		// 逃离LIKE条件通配符
		if ($like === TRUE)
		{
			$str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
		}

		return $str;
	}

	// --------------------------------------------------------------------

	/**
	 * Affected Rows
	 * 受影响的列 mysql_sffected_rows($this->conn_id)
	 * @access	public
	 * @return	integer
	 */
	function affected_rows()
	{
		return @mysql_affected_rows($this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Insert ID
	 * 最提插入的列id, 也就是取得最近一次插入数据的id号 mysql_insert_id($this->conn_id)
	 * @access	public
	 * @return	integer
	 */
	function insert_id()
	{
		return @mysql_insert_id($this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * "Count All" query
	 * 获取所有查询
	 * 
	 * Generates a platform-specific query string that counts all records in
	 * the specified database
	 * 生成一个平台特定的查询字符串中的所有记录计数指定的数据库
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	function count_all($table = '')
	{
		if ($table == '')
		{
			return 0;
		}
        // SELECT COUNT(*) AS  numrows from tableName;
		$query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));

		//如果记录数为0
		if ($query->num_rows() == 0)
		{
			return 0;
		}

		$row = $query->row();   //取得一行数据
		$this->_reset_select(); //重置查询条件
		return (int) $row->numrows; //返回记录总数
	}

	// --------------------------------------------------------------------

	/**
	 * List table query
	 * 清单表查询
	 * 
	 * Generates a platform-specific query string so that the table names can be fetched
	 * 生成一个特定于平台的查询字符串,以便可以获取表名
	 * 
	 * @access	private
	 * @param	boolean
	 * @return	string
	 */
	function _list_tables($prefix_limit = FALSE)
	{
		//取得数据库的所有表信息
		$sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char;

		//like 指定表名的数据
		//SHOW tables FROM databasename like '%TB%'
		if ($prefix_limit !== FALSE AND $this->dbprefix != '')
		{
			$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'";
		}

		return $sql;
	}

	// --------------------------------------------------------------------

	/**
	 * Show column query
	 * 显示查询列信息
	 * 
	 * Generates a platform-specific query string so that the column names can be fetched
	 * 生成一个特定于平台的查询字符串,所以也可以获取列名
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @return	string
	 */
	function _list_columns($table = '')
	{
		//show COLUMNS FROM tablename
		return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE);
	}

	// --------------------------------------------------------------------

	/**
	 * Field data query
	 * 现场数据查询
	 * Generates a platform-specific query so that the column data can be retrieved
	 * 所以也可以检索列数据,生成特定平台查询
	 * @access	public
	 * @param	string	the table name
	 * @return	object
	 */
	function _field_data($table)
	{
		return "DESCRIBE ".$table;
	}

	// --------------------------------------------------------------------

	/**
	 * The error message string
	 * 该错误消息字符串
	 * @access	private
	 * @return	string
	 */
	function _error_message()
	{
		return mysql_error($this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * The error message number
	 * 该错误消息的数值
	 * 
	 * @access	private
	 * @return	integer
	 */
	function _error_number()
	{
		return mysql_errno($this->conn_id);
	}

	// --------------------------------------------------------------------

	/**
	 * Escape the SQL Identifiers
	 * 逃离SQL标识符
	 * This function escapes column and table names
	 * 此功能逃脱列和表名
	 * @access	private
	 * @param	string
	 * @return	string
	 */
	function _escape_identifiers($item)
	{
		//如果为空,直接返回
		if ($this->_escape_char == '')
		{
			return $item;
		}

		//
		foreach ($this->_reserved_identifiers as $id)
		{
			//在teim中存在.加上$id的话,
			if (strpos($item, '.'.$id) !== FALSE)
			{
				// ` + `.
				// a.name;
				
				//`a`.name
				
				
				$str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);

				// remove duplicates if the user already included the escape
				// 删除重复,如果用户已经逃逸
				
				// [`]+ 如果出现多次,那么`进行替换
				
				return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
			}
		}

		//如果item中没有.
		if (strpos($item, '.') !== FALSE)
		{
			// a.name
			//`a`.`name`
			$str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
		}
		else
		{
			$str = $this->_escape_char.$item.$this->_escape_char;
		}

		// remove duplicates if the user already included the escape
		// 删除重复,如果用户已经逃逸
		return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
	}

	// --------------------------------------------------------------------

	/**
	 * From Tables
	 *
	 * This function implicitly groups FROM tables so there is no confusion
	 * about operator precedence in harmony with SQL standards
	 * 此功能隐含团队从表所以没有混乱
	 * 运算符优先级在和谐与SQL标准
	 *
	 * @access	public
	 * @param	type
	 * @return	type
	 */
	function _from_tables($tables)
	{
		if ( ! is_array($tables))
		{
			$tables = array($tables);
		}

		return '('.implode(', ', $tables).')';
	}

	// --------------------------------------------------------------------

	/**
	 * Insert statement
	 * insert 语句
	 * 
	 * Generates a platform-specific insert string from the supplied data
	 * 从所提供的数据,生成特定平台插入字符串
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the insert keys
	 * @param	array	the insert values
	 * @return	string
	 */
	function _insert($table, $keys, $values)
	{
		return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
	}

	// --------------------------------------------------------------------


	/**
	 * Replace statement
	 * 替换语句
	 * 
	 * Generates a platform-specific replace string from the supplied data
	 * 从所提供的数据,生成一个特定于平台的替换字符串
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the insert keys
	 * @param	array	the insert values
	 * @return	string
	 */
	function _replace($table, $keys, $values)
	{
		return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
	}

	// --------------------------------------------------------------------

	/**
	 * Insert_batch statement
	 * 插入批量语句
	 * 
	 * Generates a platform-specific insert string from the supplied data
	 * 从所提供的数据,生成特定平台插入字符串
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the insert keys
	 * @param	array	the insert values
	 * @return	string
	 */
	function _insert_batch($table, $keys, $values)
	{
		return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
	}

	// --------------------------------------------------------------------


	/**
	 * Update statement
	 * 更新语句
	 * 
	 * Generates a platform-specific update string from the supplied data
	 * 从所提供的数据,生成特定平台的更新字符串
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the update data
	 * @param	array	the where clause
	 * @param	array	the orderby clause
	 * @param	array	the limit clause
	 * @return	string
	 */
	function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
	{
		//对$values的值进行拼接
		foreach ($values as $key => $val)
		{
			$valstr[] = $key . ' = ' . $val;
		}

		//如果有 limit
		$limit = ( ! $limit) ? '' : ' LIMIT '.$limit;

		//如明 order by
		$orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';

		//开始拼接update 语句
		$sql = "UPDATE ".$table." SET ".implode(', ', $valstr);

		//如果有条件,where 
		$sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';

		$sql .= $orderby.$limit;

		return $sql;
	}

	// --------------------------------------------------------------------


	/**
	 * Update_Batch statement
	 * 批量更新语句
	 * 
	 * Generates a platform-specific batch update string from the supplied data
	 * 从所提供的数据,生成一个特定于平台的批量更新字串
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the update data
	 * @param	array	the where clause
	 * @return	string
	 */
	function _update_batch($table, $values, $index, $where = NULL)
	{
		$ids = array();
		
		//如果$where条件不为空,那么用空格拼接成字符串 后面加上AND
		$where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';

		//开始循环需要更新的值
		foreach ($values as $key => $val)
		{
			$ids[] = $val[$index]; //取得$val中指定的索引值

			//取得$val数组中的所有key值数组,并循环
			foreach (array_keys($val) as $field)
			{
				//拼接成 WHEN......THEN......
				//总算弄明白case when then 什么意思了,跟php 中的switch case差不多
				if ($field != $index)
				{
					$final[$field][] =  'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
				}
			}
		}

		$sql = "UPDATE ".$table." SET ";
		$cases = '';

		//整个这个循环有点没弄清楚什么情
		foreach ($final as $k => $v)
		{
			$cases .= $k.' = CASE '."\n";
			foreach ($v as $row)
			{
				$cases .= $row."\n";
			}

			$cases .= 'ELSE '.$k.' END, ';
		}

		$sql .= substr($cases, 0, -2);

		$sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';

		return $sql;
	}

	// --------------------------------------------------------------------


	/**
	 * Truncate statement
	 * 截断语句
	 * 
	 * Generates a platform-specific truncate string from the supplied data
	 * If the database does not support the truncate() command
	 * This function maps to "DELETE FROM table"
	 * 从所提供的数据,生成一个特定于平台的截断字符串
     * 如果数据库不支持的截断()命令。
     * 此功能映射到“DELETE FROM表”
	 * @access	public
	 * @param	string	the table name
	 * @return	string
	 */
	function _truncate($table)
	{
		return "TRUNCATE ".$table;
		//TRUNCATE talbename 是sql中的一个删除数据表内容的语句
		
	}

	// --------------------------------------------------------------------

	/**
	 * Delete statement
	 *
	 * Generates a platform-specific delete string from the supplied data
	 * 从所提供的数据,生成一个特定于平台的删除字符串
	 * 
	 * @access	public
	 * @param	string	the table name
	 * @param	array	the where clause
	 * @param	string	the limit clause
	 * @return	string
	 */
	function _delete($table, $where = array(), $like = array(), $limit = FALSE)
	{
		$conditions = '';

		if (count($where) > 0 OR count($like) > 0)
		{
			$conditions = "\nWHERE ";
			$conditions .= implode("\n", $this->ar_where);

			if (count($where) > 0 && count($like) > 0)
			{
				$conditions .= " AND ";
			}
			$conditions .= implode("\n", $like);
		}

		$limit = ( ! $limit) ? '' : ' LIMIT '.$limit;

		return "DELETE FROM ".$table.$conditions.$limit;
	}

	// --------------------------------------------------------------------

	/**
	 * Limit string
	 *
	 * Generates a platform-specific LIMIT clause
	 * 生成特定平台的限制条款
	 * @access	public
	 * @param	string	the sql query string
	 * @param	integer	the number of rows to limit the query to
	 * @param	integer	the offset value
	 * @return	string
	 */
	function _limit($sql, $limit, $offset)
	{
		if ($offset == 0)
		{
			$offset = '';
		}
		else
		{
			$offset .= ", ";
		}

		return $sql."LIMIT ".$offset.$limit;
	}

	// --------------------------------------------------------------------

	/**
	 * Close DB Connection
	 * 关闭数据库链接
	 * @access	public
	 * @param	resource
	 * @return	void
	 */
	function _close($conn_id)
	{
		@mysql_close($conn_id);
	}

}


/* End of file mysql_driver.php */
/* Location: ./system/database/drivers/mysql/mysql_driver.php */

  

posted @ 2013-06-04 10:57  简单--生活  阅读(1195)  评论(0编辑  收藏  举报
简单--生活(CSDN)