/system/database/DB_active_rec.php 活动记录类

<?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
 */

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

/**
 * Active Record Class
 * 活动记录类
 * 
 * This is the platform-independent base Active Record implementation class.
 * 这是独立于平台的基地活动记录的实现类。
 * @package		CodeIgniter
 * @subpackage	Drivers
 * @category	Database
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/database/
 */
class CI_DB_active_record extends CI_DB_driver {

	var $ar_select				= array(); //select语句
	var $ar_distinct			= FALSE;   //是否唯一distinct
	var $ar_from				= array(); //from数组
	var $ar_join				= array(); //json
	var $ar_where				= array(); //where条件
	var $ar_like				= array(); //like
	var $ar_groupby				= array(); //分组 
	var $ar_having				= array(); //having
	var $ar_keys				= array(); //keys
	var $ar_limit				= FALSE;   //limit
	var $ar_offset				= FALSE;   //offset
	var $ar_order				= FALSE;   //排序
	var $ar_orderby				= array(); //orderby
	var $ar_set					= array(); //更新
	var $ar_wherein				= array(); //where in
	var $ar_aliased_tables		= array(); //数据表的别名数组
	var $ar_store_array			= array(); //存储数组

	// Active Record Caching variables 活动记录缓存变量
	var $ar_caching				= FALSE;   //缓存 
	var $ar_cache_exists		= array(); //缓存后缀
	var $ar_cache_select		= array(); //缓存select
	var $ar_cache_from			= array(); //缓存的from
	var $ar_cache_join			= array(); //join
	var $ar_cache_where			= array(); //where
	var $ar_cache_like			= array(); //like
	var $ar_cache_groupby		= array(); //groupby
	var $ar_cache_having		= array(); //having
	var $ar_cache_orderby		= array(); //orderby
	var $ar_cache_set			= array(); //set
	
	var $ar_no_escape 			= array(); //escape
	var $ar_cache_no_escape     = array(); //no_escape

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

	/**
	 * Select
	 * SELECT部分
	 * Generates the SELECT portion of the query
	 * 生成的查询的SELECT部分
	 * @param	string
	 * @return	object
	 */
	public function select($select = '*', $escape = NULL)
	{
		//如果为字符串,那么切成数组
		if (is_string($select))
		{
			$select = explode(',', $select);
		}

		//循环所有select值
		foreach ($select as $val)
		{
			$val = trim($val); //去两边空格

			if ($val != '')
			{
				$this->ar_select[] = $val;         //加入到ar_select数组中去
				$this->ar_no_escape[] = $escape;   //ar_no_escape

				if ($this->ar_caching === TRUE)    //如果需要缓存
				{
					$this->ar_cache_select[] = $val;       //放入select
					$this->ar_cache_exists[] = 'select';   //缓存的后缀
					$this->ar_cache_no_escape[] = $escape; //escape
				}
			}
		}
		return $this;
	}

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

	/**
	 * Select Max
	 * 最大值
	 * 
	 * Generates a SELECT MAX(field) portion of a query
	 * 生成SELECT MAX(场)部分查询.
	 * @param	string	the field
	 * @param	string	an alias
	 * @return	object
	 */
	public function select_max($select = '', $alias = '')
	{
		return $this->_max_min_avg_sum($select, $alias, 'MAX');
	}

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

	/**
	 * Select Min
	 * 最小值
	 * Generates a SELECT MIN(field) portion of a query
	 *
	 * @param	string	the field
	 * @param	string	an alias
	 * @return	object
	 */
	public function select_min($select = '', $alias = '')
	{
		return $this->_max_min_avg_sum($select, $alias, 'MIN');
	}

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

	/**
	 * Select Average
	 * 平均值
	 * Generates a SELECT AVG(field) portion of a query
	 *
	 * @param	string	the field
	 * @param	string	an alias
	 * @return	object
	 */
	public function select_avg($select = '', $alias = '')
	{
		return $this->_max_min_avg_sum($select, $alias, 'AVG');
	}

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

	/**
	 * Select Sum
	 * 总和
	 * Generates a SELECT SUM(field) portion of a query
	 *
	 * @param	string	the field
	 * @param	string	an alias
	 * @return	object
	 */
	public function select_sum($select = '', $alias = '')
	{
		return $this->_max_min_avg_sum($select, $alias, 'SUM');
	}

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

	/**
	 * Processing Function for the four functions above:
	 * 上述四大功能的处理功能:
	 *	select_max()  //最大值
	 *	select_min()  //最小值
	 *	select_avg()  //平均值
	 *  select_sum()  //总和
	 *
	 * @param	string	the field
	 * @param	string	an alias
	 * @return	object
	 */
	protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX')
	{
		//如果select条件为空,那么直接显示错误
		if ( ! is_string($select) OR $select == '')
		{
			$this->display_error('db_invalid_query');
		}

		//strtoupper()对类型进行大写转换
		$type = strtoupper($type);

		//如果MAX, MIN, AVG, SUM 的话,就执行下去,不是就显示错误
		if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM')))
		{
			show_error('Invalid function type: 无效的函数类型'.$type);
		}

		//如果别名为空的话,生成一个表的别名
		if ($alias == '')
		{
			$alias = $this->_create_alias_from_table(trim($select));
		}

		//拼写sql语句
		//_protect_identifiers();函数在父类DB_driver.php
		$sql = $type.'('.$this->_protect_identifiers(trim($select)).') AS '.$alias;

		$this->ar_select[] = $sql; //放入到ar_select数组中去

		//判断是否需要缓存
		if ($this->ar_caching === TRUE)
		{
			$this->ar_cache_select[] = $sql;
			$this->ar_cache_exists[] = 'select';
		}

		return $this;
	}

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

	/**
	 * Determines the alias name based on the table
	 * 确定基于表的别名
	 * @param	string
	 * @return	string
	 */
	protected function _create_alias_from_table($item)
	{
		//如果$time字符串中存在一个'.'的字符串的话,那么就用点进行分割,然后返回最后一个数组元素
		if (strpos($item, '.') !== FALSE)
		{
			return end(explode('.', $item));
		}

		return $item;
	}

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

	/**
	 * DISTINCT
	 * DISTINCT
	 * Sets a flag which tells the query string compiler to add DISTINCT
	 * 设置一个标志,告诉编译的查询字符串添加不同的...
	 * @param	bool
	 * @return	object
	 */
	public function distinct($val = TRUE)
	{
		$this->ar_distinct = (is_bool($val)) ? $val : TRUE;
		return $this;
	}

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

	/**
	 * From
	 * 征收在from部分
	 * Generates the FROM portion of the query
	 * 生成的查询部分的FROM
	 * @param	mixed	can be a string or array
	 * @return	object
	 */
	public function from($from)
	{
		//对from变量进行循环,这里强制转换为数组 (array)$from;
		foreach ((array) $from as $val)
		{
			//如果值存在逗号分隔符时??
			if (strpos($val, ',') !== FALSE)
			{
				//用逗号分隔符分分割成数组
				foreach (explode(',', $val) as $v)
				{
					$v = trim($v); //去空格
					$this->_track_aliases($v); //设置表的别名

					
					$this->ar_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE);

					//是否缓存
					if ($this->ar_caching === TRUE)
					{
						$this->ar_cache_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE);
						$this->ar_cache_exists[] = 'from';
					}
				}
			}
			else
			{
				$val = trim($val);

				// Extract any aliases that might exist.  We use this information
				// in the _protect_identifiers to know whether to add a table prefix
				// 提取任何可能存在的别名。我们使用这些信息
                // 在_protect_identifiers知道是否要添加表
				$this->_track_aliases($val);

				$this->ar_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE);

				if ($this->ar_caching === TRUE)
				{
					$this->ar_cache_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE);
					$this->ar_cache_exists[] = 'from';
				}
			}
		}
		return $this;
	}

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

	/**
	 * Join
	 *
	 * Generates the JOIN portion of the query
	 * 生成连接的查询部分
	 * @param	string
	 * @param	string	the join condition  联接条件
	 * @param	string	the type of join    联接类型
	 * @return	object
	 */
	public function join($table, $cond, $type = '')
	{
		//如果联接类型不为空
		if ($type != '')
		{
			//转换为大写
			$type = strtoupper(trim($type));

			//查看类型是否为LEFT, RIGHT, OUTER, INNER, LEFT OUTER, RIGTH OUTER
			if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER')))
			{
				$type = '';
			}
			else
			{
				$type .= ' ';
			}
		}

		// Extract any aliases that might exist.  We use this information
		// in the _protect_identifiers to know whether to add a table prefix
		// 提取任何可能存在的别名。我们使用这些信息
		// 在_protect_identifiers知道是否要添加表前缀
		$this->_track_aliases($table);

		// Strip apart the condition and protect the identifiers
		// 剥去除了条件和保护标识符
	    
		//\w  匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。 
        //\W  匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。 
		
		//([\w\.]+) +匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。
		//([\W\s]+) \s 匹配任何空白字符地,包括空格,制表符,换页符等等.等价于 [ \f\n\r\t\v]
        //(.+) 匹配点出现一次或多次
        
		
		
        //整体意思是将$cond变量由指定的正则进行分割
		if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match))
		{
			$match[1] = $this->_protect_identifiers($match[1]);
			$match[3] = $this->_protect_identifiers($match[3]);

			$cond = $match[1].$match[2].$match[3];
		}

		// Assemble the JOIN statement 组装的JOIN声明
		$join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;

		$this->ar_join[] = $join; //放入join数组中
		//放入缓存
		if ($this->ar_caching === TRUE)
		{
			$this->ar_cache_join[] = $join;
			$this->ar_cache_exists[] = 'join';
		}

		return $this;
	}

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

	/**
	 * Where
	 *
	 * Generates the WHERE portion of the query. Separates
	 * multiple calls with AND
	 * 生成查询的WHERE部分。分隔多个电话及
	 * @param	mixed
	 * @param	mixed
	 * @return	object
	 */
	public function where($key, $value = NULL, $escape = TRUE)
	{
		return $this->_where($key, $value, 'AND ', $escape);
	}

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

	/**
	 * OR Where
	 *
	 * Generates the WHERE portion of the query. Separates
	 * multiple calls with OR
	 * 生成WHERE条件,或操作
	 * @param	mixed
	 * @param	mixed
	 * @return	object
	 */
	public function or_where($key, $value = NULL, $escape = TRUE)
	{
		return $this->_where($key, $value, 'OR ', $escape);
	}

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

	/**
	 * Where
	 * WHERE条件
	 * Called by where() or or_where()
	 *
	 * @param	mixed
	 * @param	mixed
	 * @param	string
	 * @return	object
	 */
	protected function _where($key, $value = NULL, $type = 'AND ', $escape = NULL)
	{
		//如果key不为数组,那么将key与$value合拼为数组放入到$key中
		if ( ! is_array($key))
		{
			$key = array($key => $value);
		}

		// If the escape value was not set will will base it on the global setting
		// 如果转义值没有被设置的意志会基础上的全局设置
		if ( ! is_bool($escape))
		{
			$escape = $this->_protect_identifiers;
		}

		//开始循环所有字段
		foreach ($key as $k => $v)
		{
			//如果现在还没有$this->ar_where条件存在,那么清空$type的值
			$prefix = (count($this->ar_where) == 0 AND count($this->ar_cache_where) == 0) ? '' : $type;

			//如果值为null并且
			//$this->_has_operator($k) 测试字符串是否有一个SQL运算符
			if (is_null($v) && ! $this->_has_operator($k))
			{
				// value appears not to have been set, assign the test to IS NULL
				$k .= ' IS NULL';
			}

			//如果不为null值
			if ( ! is_null($v))
			{
				if ($escape === TRUE)
				{
					$k = $this->_protect_identifiers($k, FALSE, $escape);

					$v = ' '.$this->escape($v);
				}
				
				if ( ! $this->_has_operator($k))
				{
					$k .= ' = ';
				}
			}
			else
			{
				$k = $this->_protect_identifiers($k, FALSE, $escape);
			}

			$this->ar_where[] = $prefix.$k.$v;

			if ($this->ar_caching === TRUE)
			{
				$this->ar_cache_where[] = $prefix.$k.$v;
				$this->ar_cache_exists[] = 'where';
			}

		}

		return $this;
	}

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

	/**
	 * Where_in
	 *
	 * 生成Where_in语句
	 *
	 * Generates a WHERE field IN ('item', 'item') SQL query joined with
	 * AND if appropriate
	 *
	 * @param	string	The field to search     字段搜索
	 * @param	array	The values searched on  值搜查
	 * @return	object
	 */
	public function where_in($key = NULL, $values = NULL)
	{
		return $this->_where_in($key, $values);
	}

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

	/**
	 * Where_in_or
	 *
	 * Generates a WHERE field IN ('item', 'item') SQL query joined with
	 * OR if appropriate
	 *
	 * @param	string	The field to search
	 * @param	array	The values searched on
	 * @return	object
	 */
	public function or_where_in($key = NULL, $values = NULL)
	{
		return $this->_where_in($key, $values, FALSE, 'OR ');
	}

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

	/**
	 * Where_not_in
	 * 
	 * WHERE field NOT IN ('item','item')
	 * 
	 * Generates a WHERE field NOT IN ('item', 'item') SQL query joined
	 * with AND if appropriate
	 *
	 * @param	string	The field to search
	 * @param	array	The values searched on
	 * @return	object
	 */
	public function where_not_in($key = NULL, $values = NULL)
	{
		return $this->_where_in($key, $values, TRUE);
	}

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

	/**
	 * Where_not_in_or
	 *
	 * Generates a WHERE field NOT IN ('item', 'item') SQL query joined
	 * with OR if appropriate
	 *
	 * @param	string	The field to search
	 * @param	array	The values searched on
	 * @return	object
	 */
	public function or_where_not_in($key = NULL, $values = NULL)
	{
		return $this->_where_in($key, $values, TRUE, 'OR ');
	}

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

	/**
	 * Where_in
	 *
	 * Called by where_in, where_in_or, where_not_in, where_not_in_or
	 *
	 * @param	string	The field to search     字段搜索
	 * @param	array	The values searched on  值搜索
	 * @param	boolean	If the statement would be IN or NOT IN   如果该语句将IN或NOT IN  是否not 
	 * @param	string
	 * @return	object
	 */
	protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ')
	{
		//如果key或者value为===null时,那么直接返回
		if ($key === NULL OR $values === NULL)
		{
			return;
		}
        //如果$values不为数组,转换为数组
		if ( ! is_array($values))
		{
			$values = array($values);
		}

		$not = ($not) ? ' NOT' : ''; //是否需要加NOT

		//将所有值放入到ar_wherein数组中去
		foreach ($values as $value)
		{
			$this->ar_wherein[] = $this->escape($value);
		}
        //如果还没有一条where条件,那么$type就应该为空值了
		$prefix = (count($this->ar_where) == 0) ? '' : $type;

		//
		$where_in = $prefix . $this->_protect_identifiers($key) . $not . " IN (" . implode(", ", $this->ar_wherein) . ") ";

		$this->ar_where[] = $where_in; //放入到where条件中去
		if ($this->ar_caching === TRUE)
		{
			$this->ar_cache_where[] = $where_in;
			$this->ar_cache_exists[] = 'where';
		}

		// reset the array for multiple calls 重置阵列多个电话
		$this->ar_wherein = array();
		return $this;
	}

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

	/**
	 * Like
	 * 
	 * Like 条件  
	 * AND field like '%keyword%'
	 * 
	 * Generates a %LIKE% portion of the query. Separates
	 * multiple calls with AND
	 *
	 * @param	mixed
	 * @param	mixed
	 * @return	object
	 */
	public function like($field, $match = '', $side = 'both')
	{
		return $this->_like($field, $match, 'AND ', $side);
	}

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

	/**
	 * Not Like
	 * 
	 * AND fieldName Not like '%keyword%' 
	 *
	 * Generates a NOT LIKE portion of the query. Separates
	 * multiple calls with AND
	 *
	 * @param	mixed
	 * @param	mixed
	 * @return	object
	 */
	public function not_like($field, $match = '', $side = 'both')
	{
		return $this->_like($field, $match, 'AND ', $side, 'NOT');
	}

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

	/**
	 * OR Like
	 * 
	 * OR fieldName like '%keyword%'
	 *
	 * Generates a %LIKE% portion of the query. Separates
	 * multiple calls with OR
	 *
	 * @param	mixed
	 * @param	mixed
	 * @return	object
	 */
	public function or_like($field, $match = '', $side = 'both')
	{
		return $this->_like($field, $match, 'OR ', $side);
	}

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

	/**
	 * OR Not Like
	 *
	 * OR fileName Not like '%keyword%'
	 *
	 * Generates a NOT LIKE portion of the query. Separates
	 * multiple calls with OR
	 *
	 * @param	mixed
	 * @param	mixed
	 * @return	object
	 */
	public function or_not_like($field, $match = '', $side = 'both')
	{
		return $this->_like($field, $match, 'OR ', $side, 'NOT');
	}

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

	/**
	 * Like
	 *
	 * Called by like() or orlike()
	 *
	 * @param	mixed
	 * @param	mixed
	 * @param	string
	 * @return	object
	 */
	protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '')
	{
		//如果$field不为数组,那么将$filld与$match组成成一个数组赋值给$field
		if ( ! is_array($field))
		{
			$field = array($field => $match);
		}

		//开始循环
		foreach ($field as $k => $v)
		{
			$k = $this->_protect_identifiers($k);

			//如果$this->ar_like为0那么$type将为空值
			$prefix = (count($this->ar_like) == 0) ? '' : $type;

			//
			$v = $this->escape_like_str($v);
			
			//如要$side为none时,那么不用百分号
			if ($side == 'none')
			{
				$like_statement = $prefix." $k $not LIKE '{$v}'";
			}
			//before前面用百分号
			elseif ($side == 'before')
			{
				$like_statement = $prefix." $k $not LIKE '%{$v}'";
			}
			//after 后面用百分号
			elseif ($side == 'after')
			{
				$like_statement = $prefix." $k $not LIKE '{$v}%'";
			}
			else
			{
				//其它情况两边都用百分号
				$like_statement = $prefix." $k $not LIKE '%{$v}%'";
			}

			// some platforms require an escape sequence definition for LIKE wildcards
			// 有些平台需要一个转义序列定义LIKE通配符
			// $this->_like_escape_str 在父类
			if ($this->_like_escape_str != '')
			{
				$like_statement = $like_statement.sprintf($this->_like_escape_str, $this->_like_escape_chr);
			}

			$this->ar_like[] = $like_statement; //放入到$ar_like数组中
			if ($this->ar_caching === TRUE)
			{
				$this->ar_cache_like[] = $like_statement;
				$this->ar_cache_exists[] = 'like';
			}

		}
		return $this;
	}

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

	/**
	 * GROUP BY
	 * group by 分组语句
	 * @param	string
	 * @return	object
	 */
	public function group_by($by)
	{
		//如果为字符串
		if (is_string($by))
		{
			//进行分组
			$by = explode(',', $by);
		}
        
		//开始循环
		foreach ($by as $val)
		{
			$val = trim($val); //去空格

			if ($val != '')
			{
				//将值放入到$this->ar_groupby数组中去
				$this->ar_groupby[] = $this->_protect_identifiers($val);
				
				//如果可以为缓存
				if ($this->ar_caching === TRUE)
				{
					$this->ar_cache_groupby[] = $this->_protect_identifiers($val);
					$this->ar_cache_exists[] = 'groupby';
				}
			}
		}
		return $this;
	}

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

	/**
	 * Sets the HAVING value
	 * 设置值为
	 * Separates multiple calls with AND
	 * 分隔多个电话和
	 * @param	string
	 * @param	string
	 * @return	object
	 */
	public function having($key, $value = '', $escape = TRUE)
	{
		return $this->_having($key, $value, 'AND ', $escape);
	}

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

	/**
	 * Sets the OR HAVING value
	 *
	 * Separates multiple calls with OR
	 *
	 * @param	string
	 * @param	string
	 * @return	object
	 */
	public function or_having($key, $value = '', $escape = TRUE)
	{
		return $this->_having($key, $value, 'OR ', $escape);
	}

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

	/**
	 * Sets the HAVING values
	 * 
	 * HAVING 可以让条件与统计函数在一起 
     * select Customer, SUM(OrderPrice) FROM GROUP BY Costomer HAVING SUM(OrderPrice) < 2000
	 * Called by having() or or_having()
	 *
	 * @param	string
	 * @param	string
	 * @return	object
	 */
	protected function _having($key, $value = '', $type = 'AND ', $escape = TRUE)
	{
		//如果不为数组
		if ( ! is_array($key))
		{
			$key = array($key => $value);
		}

		//循环
		foreach ($key as $k => $v)
		{
			//如果$this->ar_having为0,那么不需要$type
			$prefix = (count($this->ar_having) == 0) ? '' : $type;

			if ($escape === TRUE)
			{
				$k = $this->_protect_identifiers($k);
			}

			//如果不为一个sql的运算符的话,那么就用=号链接
			if ( ! $this->_has_operator($k))
			{
				$k .= ' = ';
			}

			if ($v != '')
			{
				$v = ' '.$this->escape($v);
			}

			$this->ar_having[] = $prefix.$k.$v;
			if ($this->ar_caching === TRUE)
			{
				$this->ar_cache_having[] = $prefix.$k.$v;
				$this->ar_cache_exists[] = 'having';
			}
		}

		return $this;
	}

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

	/**
	 * Sets the ORDER BY value
	 * 设置 ORDER BY 值
	 * @param	string
	 * @param	string	direction: asc or desc 方向:ASC或DESC
	 * @return	object
	 */
	public function order_by($orderby, $direction = '')
	{
		//如果方向为 random的话
		if (strtolower($direction) == 'random')
		{
			$orderby = ''; // Random results want or don't need a field name 随机结果想要或不需要的字段名
			$direction = $this->_random_keyword;
		}
		elseif (trim($direction) != '')
		{
		    //查看是否为 ASC 或者 DESC
			$direction = (in_array(strtoupper(trim($direction)), array('ASC', 'DESC'), TRUE)) ? ' '.$direction : ' ASC';
		}


		//查看是否有逗号,刟要有
		if (strpos($orderby, ',') !== FALSE)
		{
			$temp = array();
			//分割
			foreach (explode(',', $orderby) as $part)
			{
				//去空格
				$part = trim($part);
				//查看$part是否存表别名数组中是否已经存在
				if ( ! in_array($part, $this->ar_aliased_tables))
				{
					$part = $this->_protect_identifiers(trim($part));
				}
				//放入到$temp数组中去
				$temp[] = $part;
			}
			//将$temp数组进行拼字字符串
			$orderby = implode(', ', $temp);
		}
		else if ($direction != $this->_random_keyword)
		{
			$orderby = $this->_protect_identifiers($orderby);
		}
        
		$orderby_statement = $orderby.$direction;

		$this->ar_orderby[] = $orderby_statement;
		if ($this->ar_caching === TRUE)
		{
			$this->ar_cache_orderby[] = $orderby_statement;
			$this->ar_cache_exists[] = 'orderby';
		}

		return $this;
	}

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

	/**
	 * Sets the LIMIT value
	 * 设置limit 值
	 * @param	integer	the limit value
	 * @param	integer	the offset value
	 * @return	object
	 */
	public function limit($value, $offset = '')
	{
		$this->ar_limit = (int) $value;

		if ($offset != '')
		{
			$this->ar_offset = (int) $offset;
		}

		return $this;
	}

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

	/**
	 * Sets the OFFSET value
	 * 设置 offset值
	 * @param	integer	the offset value
	 * @return	object
	 */
	public function offset($offset)
	{
		$this->ar_offset = $offset;
		return $this;
	}

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

	/**
	 * The "set" function.  Allows key/value pairs to be set for inserting or updating
	 *
	 * @param	mixed
	 * @param	string
	 * @param	boolean
	 * @return	object
	 */
	public function set($key, $value = '', $escape = TRUE)
	{
		$key = $this->_object_to_array($key); //进行对象到数组的转换

		//如果key值不为数组,转换为数组
		if ( ! is_array($key))
		{
			$key = array($key => $value);
		}

		//开始循环
		foreach ($key as $k => $v)
		{
			if ($escape === FALSE)
			{
				$this->ar_set[$this->_protect_identifiers($k)] = $v;
			}
			else
			{
				$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
			}
		}

		return $this;
	}

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

	/**
	 * Get
	 * 
	 * Compiles the select statement based on the other functions called
	 * and runs the query
	 * 
	 * 编译select语句的基础上的其他功能称为和运行查询
	 * 
	 * @param	string	the table
	 * @param	string	the limit clause
	 * @param	string	the offset clause
	 * @return	object
	 */
	public function get($table = '', $limit = null, $offset = null)
	{
		if ($table != '')
		{
			$this->_track_aliases($table); //取别名
			$this->from($table); 
		}

		if ( ! is_null($limit))
		{
			$this->limit($limit, $offset);
		}

		$sql = $this->_compile_select(); //生成sql语句

		//执行
		$result = $this->query($sql);
		$this->_reset_select(); //重置活动记录值
		return $result;
	}

	/**
	 * "Count All Results" query
	 * “伯爵所有结果”查询
	 * 
	 * Generates a platform-specific query string that counts all records
	 * returned by an Active Record query.
	 * 生成一个特定于平台的查询字符串中的所有记录计数
     * 活动记录查询返回。
	 * @param	string
	 * @return	string
	 */
	public function count_all_results($table = '')
	{
		if ($table != '')
		{
			$this->_track_aliases($table); //取表的别名
			$this->from($table);           //设置from
		}

		//编译sql语句
		$sql = $this->_compile_select($this->_count_string . $this->_protect_identifiers('numrows'));

		$query = $this->query($sql); //执行
		$this->_reset_select();      //重置

		//如果受影响的记录数为0,直接返回0
		if ($query->num_rows() == 0)
		{
			return 0;
		}

		//返回row
		$row = $query->row();
		return (int) $row->numrows; //返回记录数
	}

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

	/**
	 * Get_Where
	 *
	 * Allows the where clause, limit and offset to be added directly
	 * 允许直接添加的where子句,限制和偏移
	 * @param	string	the where clause
	 * @param	string	the limit clause
	 * @param	string	the offset clause
	 * @return	object
	 */
	public function get_where($table = '', $where = null, $limit = null, $offset = null)
	{
		//表名
		if ($table != '')
		{
			$this->from($table);
		}

		//where条件
		if ( ! is_null($where))
		{
			$this->where($where);
		}

		//limit
		if ( ! is_null($limit))
		{
			$this->limit($limit, $offset);
		}

		//编译sql
		$sql = $this->_compile_select();

		//执行
		$result = $this->query($sql);
		$this->_reset_select(); //重置
		return $result;
	}

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

	/**
	 * Insert_Batch
	 * 插入_批
	 * Compiles batch insert strings and runs the queries
	 * 批量插入字符串编译并运行查询
	 * 
	 * @param	string	the table to retrieve the results from  表中检索的结果
	 * @param	array	an associative array of insert values   插入值的关联数组
	 * @return	object
	 */
	public function insert_batch($table = '', $set = NULL)
	{
		//如果$set不为空值时
		if ( ! is_null($set))
		{
			$this->set_insert_batch($set);
		}

		if (count($this->ar_set) == 0)
		{
			if ($this->db_debug)
			{
				//No valid data array.  Folds in cases where keys and values did not match up
				return $this->display_error('db_must_use_set');
			}
			return FALSE;
		}

		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}

		// Batch this baby
		for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
		{

			$sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100));

			//echo $sql;

			$this->query($sql);
		}

		$this->_reset_write();


		return TRUE;
	}

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

	/**
	 * The "set_insert_batch" function.  Allows key/value pairs to be set for batch inserts
	 * “set_insert_batch”功能。允许设置的键/值对批量插入
	 * @param	mixed
	 * @param	string
	 * @param	boolean
	 * @return	object
	 */
	public function set_insert_batch($key, $value = '', $escape = TRUE)
	{
		//对object转换为数组进行批量操作
		$key = $this->_object_to_array_batch($key);

		//数组转换
		if ( ! is_array($key))
		{
			$key = array($key => $value);
		}

		//取得$key中的当前的元素,然后
		// $key = current($key);
		// array_keys($key);
		// 
		$keys = array_keys(current($key));
		sort($keys); //排序

		//循环
		foreach ($key as $row)
		{
			//array_diff() 计算数组的差值 将第一个参数中存在,第二个参数中不存在的值进行返回
  			//计算$keys与array_keys的差值个数的总值是否大0
			//或者 
			if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0)
			{
				// batch function above returns an error on an empty array 上面的批处理功能在一个空数组返回一个错误
				$this->ar_set[] = array();
				return;
			}

			ksort($row); // puts $row in the same order as our keys $行以相同的顺序,我们的钥匙

			if ($escape === FALSE)
			{
				$this->ar_set[] =  '('.implode(',', $row).')';
			}
			else
			{
				$clean = array();

				foreach ($row as $value)
				{
					$clean[] = $this->escape($value);
				}

				$this->ar_set[] =  '('.implode(',', $clean).')';
			}
		}

		foreach ($keys as $k)
		{
			$this->ar_keys[] = $this->_protect_identifiers($k);
		}

		return $this;
	}

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

	/**
	 * Insert
	 *
	 * Compiles an insert string and runs the query
	 * 插入字符串编译并运行查询
	 * @param	string	the table to insert data into         将数据插入到表
	 * @param	array	an associative array of insert values 插入值的关联数组
	 * @return	object
	 */
	function insert($table = '', $set = NULL)
	{
		//如果set不为空
		if ( ! is_null($set))
		{
			$this->set($set);
		}

		//如果ar_set的值为空
		if (count($this->ar_set) == 0)
		{
			if ($this->db_debug)
			{
				return $this->display_error('db_must_use_set');
			}
			return FALSE;
		}

		//如果$table值为空
		if ($table == '')
		{
			//如果ar_from的第一个元素也不存在
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}

		//生成insertsql语句
		//$this->_insert因为是由这各数据库类型进行定义的
		$sql = $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));

		$this->_reset_write(); //重置
		return $this->query($sql); //执行证句
		
	}

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

	/**
	 * Replace
	 *
	 * Compiles an replace into string and runs the query
	 * 字符串替换成编译并运行查询
	 * @param	string	the table to replace data into        表的数据替换成
	 * @param	array	an associative array of insert values 插入值的关联数组
	 * @return	object
	 */
	public function replace($table = '', $set = NULL)
	{
		if ( ! is_null($set))
		{
			$this->set($set);
		}

		if (count($this->ar_set) == 0)
		{
			if ($this->db_debug)
			{
				return $this->display_error('db_must_use_set');
			}
			return FALSE;
		}

		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}
        //进行替换
		$sql = $this->_replace($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));

		$this->_reset_write();
		return $this->query($sql);
	}

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

	/**
	 * Update
	 *
	 * Compiles an update string and runs the query
	 * 编译更新串并运行查询
	 * 
	 * @param	string	the table to retrieve the results from  表中检索的结果
	 * @param	array	an associative array of update values   更新值的关联数组
	 * @param	mixed	the where clause                        where子句
	 * @return	object
	 */
	public function update($table = '', $set = NULL, $where = NULL, $limit = NULL)
	{
		// Combine any cached components with the current statements
		// 结合任何缓存组件与当前报表
		$this->_merge_cache();

		if ( ! is_null($set))
		{
			$this->set($set);
		}
        //如果没有set的信息话
		if (count($this->ar_set) == 0)
		{
			if ($this->db_debug)
			{
				return $this->display_error('db_must_use_set');
			}
			return FALSE;
		}

		//如果$table为空值
		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}

		//如果有where条件的话
		if ($where != NULL)
		{
			$this->where($where);
		}

		
		if ($limit != NULL)
		{
			$this->limit($limit);
		}

		//$this->_update(); 是写在数据库驱动内的
		$sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit);

		$this->_reset_write();    //重置
		return $this->query($sql);
	}


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

	/**
	 * Update_Batch
	 * 更新_批
	 * Compiles an update string and runs the query
	 * 编译更新串并运行查询
	 * @param	string	the table to retrieve the results from  表中检索的结果
	 * @param	array	an associative array of update values   更新值的关联数组
	 * @param	string	the where key                           其中键
	 * @return	object
	 */
	public function update_batch($table = '', $set = NULL, $index = NULL)
	{
		// Combine any cached components with the current statements
		// 结合任何缓存组件与当前报表
		$this->_merge_cache();

		if (is_null($index))
		{
			if ($this->db_debug)
			{
				return $this->display_error('db_must_use_index');
			}

			return FALSE;
		}

		//如果$set不为null值
		if ( ! is_null($set))
		{
			$this->set_update_batch($set, $index); //批量设置update的set值
		}

		if (count($this->ar_set) == 0)
		{
			if ($this->db_debug)
			{
				return $this->display_error('db_must_use_set');
			}

			return FALSE;
		}

		//表名
		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}

		// Batch this baby
		// 批次这个宝贝
		for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
		{
			$sql = $this->_update_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->ar_set, $i, 100), $this->_protect_identifiers($index), $this->ar_where);

			$this->query($sql);
		}

		$this->_reset_write();
	}

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

	/**
	 * The "set_update_batch" function.  Allows key/value pairs to be set for batch updating
	 * “set_update_batch”功能。允许设置的键/值对批更新
	 * @param	array
	 * @param	string
	 * @param	boolean
	 * @return	object
	 */
	public function set_update_batch($key, $index = '', $escape = TRUE)
	{
		$key = $this->_object_to_array_batch($key); //批量将对象转换为数组

		if ( ! is_array($key))
		{
			// @todo error
		}

		foreach ($key as $k => $v)
		{
			$index_set = FALSE;
			$clean = array();

			foreach ($v as $k2 => $v2)
			{
				if ($k2 == $index)
				{
					$index_set = TRUE;
				}
				else
				{
					$not[] = $k.'-'.$v;
				}

				if ($escape === FALSE)
				{
					$clean[$this->_protect_identifiers($k2)] = $v2;
				}
				else
				{
					$clean[$this->_protect_identifiers($k2)] = $this->escape($v2);
				}
			}

			if ($index_set == FALSE)
			{
				return $this->display_error('db_batch_missing_index');
			}

			$this->ar_set[] = $clean;
		}

		return $this;
	}

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

	/**
	 * Empty Table
	 * 空的表名
	 * 
	 * Compiles a delete string and runs "DELETE FROM table"
	 * 删除字符串编译并运行“DELETE FROM表”
	 * 
	 * @param	string	the table to empty 表为空
	 * @return	object
	 */
	public function empty_table($table = '')
	{
		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}
		else
		{
			$table = $this->_protect_identifiers($table, TRUE, NULL, FALSE);
		}

		$sql = $this->_delete($table); //生成删除语句

		$this->_reset_write();

		return $this->query($sql);//执行
	}

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

	/**
	 * Truncate
	 * 截短
	 * 
	 * Compiles a truncate string and runs the query
	 * If the database does not support the truncate() command
	 * This function maps to "DELETE FROM table"
	 * 编译的截断字符串和运行查询
	 * 如果数据库不支持的截断()命令。
	 * 此功能映射到“DELETE FROM表”
	 *
	 * @param	string	the table to truncate 截断表
	 * @return	object
	 */
	public function truncate($table = '')
	{
		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}
		else
		{
			$table = $this->_protect_identifiers($table, TRUE, NULL, FALSE);
		}

		$sql = $this->_truncate($table);

		$this->_reset_write();

		return $this->query($sql);
	}

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

	/**
	 * Delete
	 * 删除
	 * 
	 * Compiles a delete string and runs the query
	 * 删除字符串编译并运行查询...
	 * 
	 * @param	mixed	the table(s) to delete from. String or array 桌删除。字符串或数组
	 * @param	mixed	the where clause
	 * @param	mixed	the limit clause
	 * @param	boolean
	 * @return	object
	 */
	public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE)
	{
		// Combine any cached components with the current statements
		// 结合任何缓存组件与当前报表
		$this->_merge_cache();

		//如果数据表为空
		if ($table == '')
		{
			if ( ! isset($this->ar_from[0]))
			{
				if ($this->db_debug)
				{
					return $this->display_error('db_must_set_table');
				}
				return FALSE;
			}

			$table = $this->ar_from[0];
		}
		//如果数据表为数组
		elseif (is_array($table))
		{
			foreach ($table as $single_table)
			{
				$this->delete($single_table, $where, $limit, FALSE); //递归
			}

			$this->_reset_write(); //重写
			return;
		}
		else
		{
			$table = $this->_protect_identifiers($table, TRUE, NULL, FALSE);
		}

		//是否有where条件
		if ($where != '')
		{
			$this->where($where);
		}

		if ($limit != NULL)
		{
			$this->limit($limit);
		}

		//如果where条件为0,wherein条件为0,like的条件为0
		if (count($this->ar_where) == 0 && count($this->ar_wherein) == 0 && count($this->ar_like) == 0)
		{
			if ($this->db_debug)
			{
				return $this->display_error('db_del_must_use_where');
			}

			return FALSE;
		}

		$sql = $this->_delete($table, $this->ar_where, $this->ar_like, $this->ar_limit);

		if ($reset_data)
		{
			$this->_reset_write(); //重写
		}

		return $this->query($sql); //执行
	}

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

	/**
	 * DB Prefix
	 * 数据库的前缀
	 * Prepends a database prefix if one exists in configuration
	 *
	 * @param	string	the table
	 * @return	string
	 */
	public function dbprefix($table = '')
	{
		if ($table == '')
		{
			$this->display_error('db_table_name_required');
		}

		return $this->dbprefix.$table;
	}

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

	/**
	 * Set DB Prefix
	 * 设置数据库的前缀
	 * Set's the DB Prefix to something new without needing to reconnect
	 *
	 * @param	string	the prefix
	 * @return	string
	 */
	public function set_dbprefix($prefix = '')
	{
		return $this->dbprefix = $prefix;
	}

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

	/**
	 * Track Aliases
	 * 轨道别名
	 * Used to track SQL statements written with aliased tables.
	 * 用于跟踪与锯齿表编写的SQL语句。
	 * @param	string	The table to inspect
	 * @return	string
	 */
	protected function _track_aliases($table)
	{
		//如果table是一个数组
		if (is_array($table))
		{
			foreach ($table as $t)
			{
				$this->_track_aliases($t); //那么进行递归操作
			}
			return;
		}

		// Does the string contain a comma?  If so, we need to separate
		// the string into discreet statements
		// 字符串是否包含一个逗号?如果是这样的话,我们需要分开
        // 串入谨慎报表
        //发果有逗号,我们进行分割操作
		if (strpos($table, ',') !== FALSE)
		{
			return $this->_track_aliases(explode(',', $table));
		}

		// if a table alias is used we can recognize it by a space
		// 如果使用表别名,我们可以辨识它的空间
		//from tableName as table
		if (strpos($table, " ") !== FALSE)
		{
			
			// if the alias is written with the AS keyword, remove it
			// 如果别名AS关键字写入,删除
			// 将AS 不管是大小写,用空格替换
			//preg_replace('/\s+AS\s+/i',' ',$table);
			$table = preg_replace('/\s+AS\s+/i', ' ', $table);

			// Grab the alias 抓住别名
			$table = trim(strrchr($table, " ")); 
			//strrchr--取得字元最后一次出现处到结尾的字符串
			//strrchr($table," ");
			//这里的$table已经是别名了

			// Store the alias, if it doesn't already exist
			// 存储别名,如果它已经不存在...
			//如果别名不存在的话,保存到ar_aliased_tables数组中去
			if ( ! in_array($table, $this->ar_aliased_tables))
			{
				$this->ar_aliased_tables[] = $table;
			}
		}
	}

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

	/**
	 * Compile the SELECT statement
	 * 编译SELECT语句
	 * 
	 * Generates a query string based on which functions were used.
	 * Should not be called directly.  The get() function calls it.
	 * 基于功能生成一个查询字符串。
     * 不应该直接调用。 get()函数调用它。
	 * @return	string
	 */
	protected function _compile_select($select_override = FALSE)
	{
		// Combine any cached components with the current statements
		// 结合任何缓存组件与当前报表
		$this->_merge_cache(); //确实是合并了

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

		// Write the "select" portion of the query
        // 写“选择”的查询部分
		if ($select_override !== FALSE)
		{
			$sql = $select_override;
		}
		else
		{
			//如果有distinct存在
			$sql = ( ! $this->ar_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';

			//是否有ar_select的值,如果没有用*
			if (count($this->ar_select) == 0)
			{
				$sql .= '*';
			}
			else
			{
				// Cycle through the "select" portion of the query and prep each column name.
				// The reason we protect identifiers here rather then in the select() function
				// is because until the user calls the from() function we don't know if there are aliases
				// 循环通过“选择”部分的每个列名的查询和准备。
				// 我们之所以在这里保护标识符而不是选择()函数
				// 是因为直到用户调用()函数,我们不知道是否有别名

				foreach ($this->ar_select as $key => $val)
				{
					$no_escape = isset($this->ar_no_escape[$key]) ? $this->ar_no_escape[$key] : NULL;
					$this->ar_select[$key] = $this->_protect_identifiers($val, FALSE, $no_escape);
				}
                //拼接字符串
				$sql .= implode(', ', $this->ar_select);
			}
		}

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

		// Write the "FROM" portion of the query
        // 添加FROM 
		if (count($this->ar_from) > 0)
		{
			$sql .= "\nFROM ";

			$sql .= $this->_from_tables($this->ar_from);
		}

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

		// Write the "JOIN" portion of the query
        //添加 JOIN语句
		if (count($this->ar_join) > 0)
		{
			$sql .= "\n";

			$sql .= implode("\n", $this->ar_join);
		}

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

		// Write the "WHERE" portion of the query
		// 如果where大于0或者like大于0 那么添加where语句
		if (count($this->ar_where) > 0 OR count($this->ar_like) > 0)
		{
			$sql .= "\nWHERE ";
		}

		$sql .= implode("\n", $this->ar_where);

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

		// Write the "LIKE" portion of the query
        //添加like
		if (count($this->ar_like) > 0)
		{
			if (count($this->ar_where) > 0)
			{
				$sql .= "\nAND ";
			}

			$sql .= implode("\n", $this->ar_like);
		}

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

		// Write the "GROUP BY" portion of the query
        // 添加group by语句
		if (count($this->ar_groupby) > 0)
		{
			$sql .= "\nGROUP BY ";

			$sql .= implode(', ', $this->ar_groupby);
		}

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

		// Write the "HAVING" portion of the query
        //添加HAVING主句
		if (count($this->ar_having) > 0)
		{
			$sql .= "\nHAVING ";
			$sql .= implode("\n", $this->ar_having);
		}

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

		// Write the "ORDER BY" portion of the query
		// 写入order by

		if (count($this->ar_orderby) > 0)
		{
			$sql .= "\nORDER BY ";
			$sql .= implode(', ', $this->ar_orderby);

			if ($this->ar_order !== FALSE)
			{
				$sql .= ($this->ar_order == 'desc') ? ' DESC' : ' ASC';
			}
		}

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

		// Write the "LIMIT" portion of the query
		//写入 limit

		if (is_numeric($this->ar_limit))
		{
			$sql .= "\n";
			$sql = $this->_limit($sql, $this->ar_limit, $this->ar_offset);
		}

		return $sql;
	}

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

	/**
	 * Object to Array
	 * 对象转换为数组
	 * 
	 * Takes an object as input and converts the class variables to array key/vals
	 * 一个对象作为输入,并将其转换类变量数组的键/丘壑
	 * @param	object
	 * @return	array
	 */
	public function _object_to_array($object)
	{
		//is_object()是否为对象
		if ( ! is_object($object))
		{
			return $object;
		}

		$array = array();
		//get_object_vars()取得对象所有方法与属性
		foreach (get_object_vars($object) as $key => $val)
		{
			// There are some built in keys we need to ignore for this conversion
			// 有一些内置的按键,我们需要忽略此转换
			//不是对象, 并且值不为数组,并且键值名不能为_parent_name
			if ( ! is_object($val) && ! is_array($val) && $key != '_parent_name')
			{
				$array[$key] = $val;
			}
		}

		return $array;
	}

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

	/**
	 * Object to Array
	 * 对象对数组
	 * 
	 * Takes an object as input and converts the class variables to array key/vals
	 * 一个对象作为输入,并将其转换类变量数组的键/丘壑
	 * 
	 * @param	object
	 * @return	array
	 */
	public function _object_to_array_batch($object)
	{
		//如查不为对象,直接返回
		if ( ! is_object($object))
		{
			return $object;
		}

		$array = array(); 
		$out = get_object_vars($object); //转为数组
		$fields = array_keys($out);      //取得所有键值,也就是字段名
		
		
        //开始循环
		foreach ($fields as $val)
		{
			// There are some built in keys we need to ignore for this conversion
			// 有一些内置的按键,我们需要忽略此转换
			if ($val != '_parent_name')
			{
				$i = 0;
				//开始循环字段中的值,
				foreach ($out[$val] as $data)
				{
					//然后簇入到$array变量中以$i做为键值,然后用$val做为子键值的二维数组
					$array[$i][$val] = $data;
					$i++;
				}
			}
		}

		return $array;
	}

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

	/**
	 * Start Cache
	 * 开始缓存
	 * Starts AR caching
	 * 启动AR缓存
	 * @return	void
	 */
	public function start_cache()
	{
		$this->ar_caching = TRUE;
	}

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

	/**
	 * Stop Cache
	 * 停止缓存
	 * 
	 * Stops AR caching
	 *
	 * @return	void
	 */
	public function stop_cache()
	{
		$this->ar_caching = FALSE;
	}

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

	/**
	 * Flush Cache
	 * 清空缓存
	 * 
	 * Empties the AR cache
	 * 清空AR缓存
	 * @access	public
	 * @return	void
	 */
	public function flush_cache()
	{
		$this->_reset_run(array(
			'ar_cache_select'		=> array(),
			'ar_cache_from'			=> array(),
			'ar_cache_join'			=> array(),
			'ar_cache_where'		=> array(),
			'ar_cache_like'			=> array(),
			'ar_cache_groupby'		=> array(),
			'ar_cache_having'		=> array(),
			'ar_cache_orderby'		=> array(),
			'ar_cache_set'			=> array(),
			'ar_cache_exists'		=> array(),
			'ar_cache_no_escape'	=> array()
		));
	}

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

	/**
	 * Merge Cache
	 * 合并缓存
	 * 
	 * When called, this function merges any cached AR arrays with
	 * locally called ones.
	 * 调用时,此功能将合并任何缓存的AR阵列与当地叫的。
	 * @return	void
	 */
	protected function _merge_cache()
	{
		//如果当前的缓存后缀为0,那么直接返回
		if (count($this->ar_cache_exists) == 0)
		{
			return;
		}

		//开始循环缓存后缀
		foreach ($this->ar_cache_exists as $val)
		{
			$ar_variable	= 'ar_'.$val;
			$ar_cache_var	= 'ar_cache_'.$val;
			
			
            //如果当前缓存的需要缓存的相应的ar_cache_$val的值为0那么直接结果该次foreach
			if (count($this->$ar_cache_var) == 0)
			{
				continue;
			}
            //将$ar_variable 和$ar_cache_var的值进行合并,并去掉重复的键值 array_unique() 
			$this->$ar_variable = array_unique(array_merge($this->$ar_cache_var, $this->$ar_variable));
		}

		// If we are "protecting identifiers" we need to examine the "from"
		// portion of the query to determine if there are any aliases
		// 如果我们保护标识“,”我们需要审视“从”
        // 的查询部分,以确定是否有任何别名

		if ($this->_protect_identifiers === TRUE AND count($this->ar_cache_from) > 0)
		{
			$this->_track_aliases($this->ar_from);
		}

		$this->ar_no_escape = $this->ar_cache_no_escape;
	}

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

	/**
	 * Resets the active record values.  Called by the get() function
	 * 重置活动记录值。 get()函数调用
	 * @param	array	An array of fields to reset 重置字段的数组
	 * @return	void
	 */
	protected function _reset_run($ar_reset_items)
	{
		foreach ($ar_reset_items as $item => $default_value)
		{
			//如果item在ar_store_array()数组中存在的话,那么设置
			if ( ! in_array($item, $this->ar_store_array))
			{
				$this->$item = $default_value;
			}
		}
	}

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

	/**
	 * Resets the active record values.  Called by the get() function
	 * 重置活动记录值。 get()函数调用
	 * @return	void
	 */
	protected function _reset_select()
	{
		$ar_reset_items = array(
			'ar_select'			=> array(),
			'ar_from'			=> array(),
			'ar_join'			=> array(),
			'ar_where'			=> array(),
			'ar_like'			=> array(),
			'ar_groupby'		=> array(),
			'ar_having'			=> array(),
			'ar_orderby'		=> array(),
			'ar_wherein'		=> array(),
			'ar_aliased_tables'	=> array(),
			'ar_no_escape'		=> array(),
			'ar_distinct'		=> FALSE,
			'ar_limit'			=> FALSE,
			'ar_offset'			=> FALSE,
			'ar_order'			=> FALSE,
		);

		$this->_reset_run($ar_reset_items);
	}

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

	/**
	 * Resets the active record "write" values.
	 * 将活动记录“写”的价值观。
	 * Called by the insert() update() insert_batch() update_batch() and delete() functions
	 * insert()方法调用的更新()insert_batch,()update_batch,()和delete()函数
	 * @return	void
	 */
	protected function _reset_write()
	{
		$ar_reset_items = array(
			'ar_set'		=> array(),
			'ar_from'		=> array(),
			'ar_where'		=> array(),
			'ar_like'		=> array(),
			'ar_orderby'	=> array(),
			'ar_keys'		=> array(),
			'ar_limit'		=> FALSE,
			'ar_order'		=> FALSE
		);

		$this->_reset_run($ar_reset_items);
	}
}

/* End of file DB_active_rec.php */
/* Location: ./system/database/DB_active_rec.php */

  

posted @ 2013-06-03 21:07  简单--生活  阅读(387)  评论(0)    收藏  举报
简单--生活(CSDN)