thinkphp3.2源码-----Driver.class.php

来源:互联网 发布:知峰保暖内衣价格 编辑:程序博客网 时间:2024/04/29 12:09

原文地址:http://blog.csdn.net/lijingshan34/article/details/51979335#comments

<?php// +----------------------------------------------------------------------// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]// +----------------------------------------------------------------------// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.// +----------------------------------------------------------------------// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )// +----------------------------------------------------------------------// | Author: liu21st <liu21st@gmail.com>// +----------------------------------------------------------------------namespace Think\Db;use Think\Config;use Think\Debug;use Think\Log;use PDO;abstract class Driver {    // PDO操作实例    protected $PDOStatement = null; // 当前连接实例  也是结果集    // 当前操作所属的模型名    protected $model      = '_think_';// 所属模型    // 当前SQL指令    protected $queryStr   = '';// sql 语句    protected $modelSql   = array(); // 这个应该是事务类型的 sql 语句    // 最后插入ID    protected $lastInsID  = null; // getlastSql就是 返回当前数据ID    // 返回或者影响记录数    protected $numRows    = 0;// 获取影响的行数    // 事务指令数    protected $transTimes = 0;// 指令执行次数    // 错误信息    protected $error      = ''; // 错误信息    // 数据库连接ID 支持多个连接    protected $linkID     = array(); // 多连接    // 当前连接ID    protected $_linkID    = null; // 当前 单连接    // 数据库连接参数配置    protected $config     = array( // 神奇的配置文件        'type'              =>  '',     // 数据库类型  一般来说用的最多了        'hostname'          =>  '127.0.0.1', // 服务器地址        'database'          =>  '',          // 数据库名        'username'          =>  '',      // 用户名        'password'          =>  '',          // 密码        'hostport'          =>  '',        // 端口        'dsn'               =>  '', //       数据库连接字符串        'params'            =>  array(), // 数据库连接参数        'charset'           =>  'utf8',      // 数据库编码默认采用utf8        'prefix'            =>  '',    // 数据库表前缀        'debug'             =>  false, // 数据库调试模式        'deploy'            =>  0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)  简单的说,就是 分布式        'rw_separate'       =>  false,       // 数据库读写是否分离 主从式有效  读写分离,主从有效        'master_num'        =>  1, // 读写分离后 主服务器数量  默认主服务器 1        'slave_no'          =>  '', // 指定从服务器序号  默认 随机轮询        'db_like_fields'    =>  '',  // 连接区域    );    // 数据库表达式    protected $exp = array('eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN','not in'=>'NOT IN','between'=>'BETWEEN','not between'=>'NOT BETWEEN','notbetween'=>'NOT BETWEEN');    // 表达式 内部转义使用    // 查询表达式    protected $selectSql  = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';    // 查询语句的表达式,据说这个语句比较复杂    // 查询次数    protected $queryTimes   =   0; // 查询次数    // 执行次数    protected $executeTimes =   0;// 执行次数    // PDO连接参数    protected $options = array( // 默认 PDO连接的参数        PDO::ATTR_CASE              =>  PDO::CASE_LOWER,        PDO::ATTR_ERRMODE           =>  PDO::ERRMODE_EXCEPTION,        PDO::ATTR_ORACLE_NULLS      =>  PDO::NULL_NATURAL,        PDO::ATTR_STRINGIFY_FETCHES =>  false,    );    protected $bind         =   array(); // 参数绑定 格外配置的参数    /**     * 架构函数 读取数据库配置信息     * @access public     * @param array $config 数据库配置数组     */    public function __construct($config=''){ // 获取参数配置 从输入参数的角度上可以看出,这个就是参数配置了        if(!empty($config)) {            $this->config   =   array_merge($this->config,$config);            if(is_array($this->config['params'])){                $this->options  =   $this->config['params'] + $this->options; // 这个 跟上面的那个其实是差不多的            }        }    }    /**     * 连接数据库方法     * @access public     */    public function connect($config='',$linkNum=0,$autoConnection=false) { // 数据库连接,支持 单独配置 数据库选择从库,自动连接        if ( !isset($this->linkID[$linkNum]) ) { // 如果有数据库连接 下面的 else 就直接返回,否则,连接上,在返回            if(empty($config))  $config =   $this->config; // 先处理当前的配置项目            try{ // 大大的异常处理,就是搞不定,就用这个                if(empty($config['dsn'])) { // 看看 用什么 方式进行连接                    $config['dsn']  =   $this->parseDsn($config);//                }                if(version_compare(PHP_VERSION,'5.3.6','<=')){                    // 禁用模拟预处理语句                    $this->options[PDO::ATTR_EMULATE_PREPARES]  =   false; // 进行解析 防止注入的                }                $this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$this->options);// 进行参数配置的连接            }catch (\PDOException $e) {                if($autoConnection){ // 判读是否自动ianj                    trace($e->getMessage(),'','ERR');                    return $this->connect($autoConnection,$linkNum); // 进行自动连接的返回                }elseif($config['debug']){                    E($e->getMessage());// 直接返回问题                }            }        }        return $this->linkID[$linkNum];    }    /**     * 解析pdo连接的dsn信息     * @access public     * @param array $config 连接信息     * @return string     */    protected function parseDsn($config){} // 调用 其它的函数的解析类  在子类中执行    /**     * 释放查询结果     * @access public     */    public function free() { // 清空结果集        $this->PDOStatement = null;    }    /**     * 执行查询 返回数据集     * @access public     * @param string $str  sql指令     * @param boolean $fetchSql  不执行只是获取SQL     * @return mixed     */    public function query($str,$fetchSql=false) {        // 第一步:初始化连接        $this->initConnect(false);// 初始化连接        if ( !$this->_linkID ) return false;// 失败 返回 false        // 第二步:处理 sql 语句        $this->queryStr     =   $str;// 如果有 str 字符串,就 复制给 执行语句 句柄        if(!empty($this->bind)){ // 如果没有 参数就不执行            $that   =   $this;// 赋值当前对象            $this->queryStr =   strtr($this->queryStr,array_map(function($val) use($that){ return '\''.$that->escapeString($val).'\''; },$this->bind));// 参数执行, 外加过滤        }        // 第二步:小插曲,可以直接返回语句,半路的功能        if($fetchSql){// 如果没有            return $this->queryStr; // 这个query 可以返回参数 ,牛叉        }        // 第三步: 准备 参数 跟日志        //释放前次的查询结果        if ( !empty($this->PDOStatement) ) $this->free(); // 清空仓库        $this->queryTimes++;// 记录查询次数        N('db_query',1); // 兼容代码 更新记录日志        // 调试开始        // 第四步:开始 查询执行        $this->debug(true);// 这个我看过了,其实就是一个 记录操作日志        $this->PDOStatement = $this->_linkID->prepare($str); // 破解 准备        if(false === $this->PDOStatement){//  如果没找到的话,            $this->error();// 报错            return false;        }        foreach ($this->bind as $key => $val) {// 绑定参数解析            if(is_array($val)){                $this->PDOStatement->bindValue($key, $val[0], $val[1]);            }else{                $this->PDOStatement->bindValue($key, $val);            }        }        $this->bind =   array();// 清空绑定参数        try{            $result =   $this->PDOStatement->execute(); // 开始执行 获取            // 调试结束            $this->debug(false);// 关闭 调试 记录运行内存 跟时间            if ( false === $result ) {// 没有结果                $this->error();// 返回错误                return false;            } else {                return $this->getResult();// 获取返回结果            }        }catch (\PDOException $e) {            $this->error();// 返回异步错误信息            return false;        }        // 返回结果,    }    /**     * 执行语句     * @access public     * @param string $str  sql指令     * @param boolean $fetchSql  不执行只是获取SQL     * @return mixed     * pdo 的执行     */    public function execute($str,$fetchSql=false) {        $this->initConnect(true);        if ( !$this->_linkID ) return false;        $this->queryStr = $str;        if(!empty($this->bind)){            $that   =   $this;            $this->queryStr =   strtr($this->queryStr,array_map(function($val) use($that){ return '\''.$that->escapeString($val).'\''; },$this->bind));        }        if($fetchSql){            return $this->queryStr;        }        //释放前次的查询结果        if ( !empty($this->PDOStatement) ) $this->free();        $this->executeTimes++;        N('db_write',1); // 兼容代码        // 记录开始执行时间        $this->debug(true);        $this->PDOStatement =   $this->_linkID->prepare($str);        if(false === $this->PDOStatement) {            $this->error();            return false;        }        foreach ($this->bind as $key => $val) {            if(is_array($val)){                $this->PDOStatement->bindValue($key, $val[0], $val[1]);            }else{                $this->PDOStatement->bindValue($key, $val);            }        }        $this->bind =   array();        try{            $result =   $this->PDOStatement->execute();            // 调试结束            $this->debug(false);            if ( false === $result) {                $this->error();                return false;            } else {                $this->numRows = $this->PDOStatement->rowCount();                if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {                    $this->lastInsID = $this->_linkID->lastInsertId();                }                return $this->numRows;            }        }catch (\PDOException $e) {            $this->error();            return false;        }    }    // 总结 这个 跟 pdo 的query 还有 execute 都可以 类似的时间    /**     * 启动事务     * @access public     * @return void     */    public function startTrans() {// 启动事务,不是开启事务        $this->initConnect(true);        if ( !$this->_linkID ) return false;        //数据rollback 支持        if ($this->transTimes == 0) {            $this->_linkID->beginTransaction(); // 开启事件        }        $this->transTimes++;        return ;    }    /**     * 用于非自动提交状态下面的查询提交     * @access public     * @return boolean     * 事务提交     */    public function commit() {        if ($this->transTimes > 0) {            $result = $this->_linkID->commit();            $this->transTimes = 0;            if(!$result){                $this->error();                return false;            }        }        return true;    }    /**     * 事务回滚     * @access public     * @return boolean     * 封装的事务回滚     */    public function rollback() {        if ($this->transTimes > 0) {            $result = $this->_linkID->rollback();            $this->transTimes = 0;            if(!$result){                $this->error();                return false;            }        }        return true;    }    /**     * 获得所有的查询数据     * @access private     * @return array     * 获取结果集     */    private function getResult() {        //返回数据集        $result =   $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);        $this->numRows = count( $result );        return $result;    }    /**     * 获得查询次数     * @access public     * @param boolean $execute 是否包含所有查询     * @return integer     * 获得查询次数     */    public function getQueryTimes($execute=false){        return $execute?$this->queryTimes+$this->executeTimes:$this->queryTimes;    }    /**     * 获得执行次数     * @access public     * @return integer     * 获取执行次数     */    public function getExecuteTimes(){        return $this->executeTimes;    }    /**     * 关闭数据库     * @access public     * 关闭数据库连接     */    public function close() {        $this->_linkID = null;    }    /**     * 数据库错误信息     * 并显示当前的SQL语句     * @access public     * @return string     */    public function error() {        if($this->PDOStatement) {            $error = $this->PDOStatement->errorInfo();            $this->error = $error[1].':'.$error[2];        }else{            $this->error = '';        }        if('' != $this->queryStr){            $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;        }        // 处理错误信息 完成        // 记录错误日志        trace($this->error,'','ERR');// 记录运行信息        if($this->config['debug']) {// 开启数据库调试模式            E($this->error);        }else{            return $this->error;        }    }    /**     * 参数绑定     * @access protected     * @param string $name 绑定参数名     * @param mixed $value 绑定值     * @return void     */    protected function bindParam($name,$value){        $this->bind[':'.$name]  =   $value;    }// 总结 上面的这些东西,基本上还是 sql 语句里面自带的东西了,// 下面,就是呵呵了    /**     * 设置锁机制     * @access protected     * @return string     * 这个锁,我也是醉了     */    protected function parseLock($lock=false) {        return $lock?   ' FOR UPDATE '  :   '';    }    /**     * set分析     * @access protected     * @param array $data     * @return string     */    protected function parseSet($data) {        foreach ($data as $key=>$val){// 循环处理数据            if(is_array($val) && 'exp' == $val[0]){// 数组形式的处理                $set[]  =   $this->parseKey($key).'='.$val[1];            }elseif(is_null($val)){// 为空兼容处理                $set[]  =   $this->parseKey($key).'=NULL';            }elseif(is_scalar($val)) {// 过滤非标量数据                // 如果给出的变量参数var是一个标量,则is_scalar()函数将返回true,否则返回false。                // 标量变量是指那些包含了整型(integer)、浮点型(float)、字符串(string)或布尔型(boolean)的变量,而数组(array)、对象(object)和resource资源类型则不是标量。                if(0===strpos($val,':') && in_array($val,array_keys($this->bind)) ){                    $set[]  =   $this->parseKey($key).'='.$this->escapeString($val);                }else{                    $name   =   count($this->bind);                    $set[]  =   $this->parseKey($key).'=:'.$name;                    $this->bindParam($name,$val);                }            }        }        return ' SET '.implode(',',$set); // 特别喜欢这里 嘿嘿, 比自己组合强多了    }    // 总结,这个 SET 应该是为了 更新数据而设置,估计不同的更新方式不一样,出现时的解析方式不一样了    /**     * 字段名分析     * @access protected     * @param string $key     * @return string     * 这个不科学啊     */    protected function parseKey(&$key) {        return $key;// 太简单了    }    /**     * value分析     * @access protected     * @param mixed $value     * @return string     * 不错,今天我们开始继续更新 ,处理了个 Value 简直就是各种的 if else 啊     */    protected function parseValue($value) {        if(is_string($value)) {// 如果 是字符串 解析            // 如果没有冒号 并且 在 对应绑定的参数里面  就是 加不加斜杠的问题            $value =  strpos($value,':') === 0 && in_array($value,array_keys($this->bind))? $this->escapeString($value) : '\''.$this->escapeString($value).'\'';        }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){ // 如果是数组            $value =  $this->escapeString($value[1]); // 返回加入反斜杠的        }elseif(is_array($value)) {            // 此处是个位置的状态,如果有知道的同学,可以回复我一下,嘿嘿,感谢了            $value =  array_map(array($this, 'parseValue'),$value);// 有点递归调用的感觉        }elseif(is_bool($value)){ // 将真假 转换成为 1 0            $value =  $value ? '1' : '0';        }elseif(is_null($value)){// 空 转换成为 null            $value =  'null';        }        return $value;    }    /**     * field分析     * @access protected     * @param mixed $fields     * @return string     * 默认解析字段     */    protected function parseField($fields) {        if(is_string($fields) && '' !== $fields) { // 字段如果是 字符串,并且 , 分割,就变回了 数组了            $fields    = explode(',',$fields);        }// 情况1 完成        // 哥,我错了,我发现你的用心良苦了,搞了了半天,是提前预处理啊        if(is_array($fields)) {            // 完善数组方式传字段名的支持            // 支持 'field1'=>'field2' 这样的字段别名定义            $array   =  array(); // 整理临时仓库            foreach ($fields as $key=>$field){ //                if(!is_numeric($key)) // 如果是 非数字key 说白了 就是为了 那个啥 as 别名而已了                    $array[] =  $this->parseKey($key).' AS '.$this->parseKey($field);                else                    $array[] =  $this->parseKey($field);// 普通解析            }            $fieldsStr = implode(',', $array); // 然后在弄回去,有意思啊        }else{            $fieldsStr = '*';        }// 情况2 完成        //TODO 如果是查询全部字段,并且是join的方式,那么就把要查的表加个别名,以免字段被覆盖        return $fieldsStr; // 不过这种不相信任何人的兼容姿态的确不错,值得鼓励!    }// 2016 01 26 继续,嘿嘿    /**     * table分析     * @access protected     * @param mixed $table     * @return string     * 解析table 这个 神器的设备     */    protected function parseTable($tables) {        if(is_array($tables)) {// 支持别名定义 数组样式 跟 非数组样式            $array   =  array();            foreach ($tables as $table=>$alias){                if(!is_numeric($table)) // 增加了别名的一个判定                    $array[] =  $this->parseKey($table).' '.$this->parseKey($alias);                else // 普通的 tables                    $array[] =  $this->parseKey($alias);            }            $tables  =  $array; // 这个是为了 包含多个表做准备        }elseif(is_string($tables)){            $tables  =  explode(',',$tables);            array_walk($tables, array(&$this, 'parseKey'));// 又是个遍历,数组式的遍历        }        return implode(',',$tables);// 又是个拼合啊Q    }    // 其实,基本上可以说是秒懂了    // jingshan_user user, dage_score score    // jingshan_user, dage_age    // 处理 完成就是上述风格了。    /**     * where分析     * @access protected     * @param mixed $where     * @return string     * 这个可是个大活啊,嘿嘿     */    protected function parseWhere($where) {        $whereStr = ''; // 首选准备好 仓库 【临时的】        if(is_string($where)) { // 如果是写好的语句,那么 就直接了            // 直接使用字符串条件            $whereStr = $where; // 其实这个不太常用,我个人不常用,嘿嘿        }else{ // 使用数组表达式 那么表达式的 来了            $operate  = isset($where['_logic'])?strtoupper($where['_logic']):''; // 不同 语句之间的逻辑关系            if(in_array($operate,array('AND','OR','XOR'))){ // 符合规则,就按照规则完                // 定义逻辑运算规则 例如 OR XOR AND NOT                $operate    =   ' '.$operate.' ';                unset($where['_logic']);            }else{ // 否则 默认                // 默认进行 AND 运算                $operate    =   ' AND ';            }// 先处理 逻辑 清空 为下一步遍历 做准备            foreach ($where as $key=>$val){ // 变量 里面的数据                if(is_numeric($key)){ // 如果是数字的 话,其实,按照通常的角度,也就是 没有进行                    $key  = '_complex';//                }// 搞了半天,这个是为了匹配预处理机制啊,嘿嘿                //$Model->where("id=%d and username='%s' and xx='%f'",array($id,$username,$xx))->select();                // $Model->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();                if(0===strpos($key,'_')) {                    // 解析特殊条件表达式                    $whereStr   .= $this->parseThinkWhere($key,$val);                    // 也就是说,这个是搞不定的,那么,外包了,哈哈哈                }else{                    // 查询字段的安全过滤                    // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){                    //     E(L('_EXPRESS_ERROR_').':'.$key);                    // }                    // 多条件支持                    // 过滤,自己都给他删除了,还弄个毛线呢,嘿嘿                    $multi  = is_array($val) &&  isset($val['_multi']);// 支持 单个字段 多条件查询                    // 也就是说,如果,值是数组, 那么就是可以多条件查询的,并且含有多条件查询的标识                    $key    = trim($key); // 清空 两侧空格                    if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段                        // 多字段 或条件 相同数值的简写                        $array =  explode('|',$key); // 解析这种方式                        $str   =  array();                        foreach ($array as $m=>$k){ // 一般情况下的 array 没啥呢 就是多个字段的 轮询                            $v =  $multi?$val[$m]:$val; // 这里传入的k 其实也是字段 的名字,                            $str[]   = $this->parseWhereItem($this->parseKey($k),$v);                        }                        $whereStr .= '( '.implode(' OR ',$str).' )';                    }elseif(strpos($key,'&')){                        // 多字段 与条件 相同数值的简写                        $array =  explode('&',$key);                        $str   =  array();                        foreach ($array as $m=>$k){                            $v =  $multi?$val[$m]:$val;                            $str[]   = '('.$this->parseWhereItem($this->parseKey($k),$v).')';                        }                        $whereStr .= '( '.implode(' AND ',$str).' )';                    }else{                        // 各种条目外包                        $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);                    }                }                $whereStr .= $operate;// 拼接            }            $whereStr = substr($whereStr,0,-strlen($operate)); // 删掉最后一个 组合, 为啥不哦那个 implode 呢,我觉得更靠谱,嘿嘿        }        return empty($whereStr)?'':' WHERE '.$whereStr;    }    // where子单元分析    // 其实写这个 要具有较高的mysql 基础,这样才能做一良好 的映射    protected function parseWhereItem($key,$val) { // 基本上应该就是 字段名 + 字段的数值        $whereStr = ''; // 这个是一个单独的分析了 大的数组里面的 子数组,或者数值的一个分析        if(is_array($val)) { // 弄个半天,先解析困难的            if(is_string($val[0])) { // 也就是自己规定的 字段  如果是表达式 的                $exp=strtolower($val[0]);// 转义表达式                if(preg_match('/^(eq|neq|gt|egt|lt|elt)$/',$exp)) { // 比较运算                    $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]); // 一个简单的数组映射 就过去了,牛叉                }elseif(preg_match('/^(notlike|like)$/',$exp)){// 模糊查找                    if(is_array($val[1])) { // 如果表达式里面的值 还是 数组,这个比较疯掉了                        $likeLogic  =   isset($val[2])?strtoupper($val[2]):'OR'; // 并且还有更多的逻辑,                        // 这个是针对于 like or notlike 的特殊用法,嘿嘿                        if(in_array($likeLogic,array('AND','OR','XOR'))){                            $like       =   array();                            foreach ($val[1] as $item){                                $like[] = $key.' '.$this->exp[$exp].' '.$this->parseValue($item);                            }                            $whereStr .= '('.implode(' '.$likeLogic.' ',$like).')';                        }                    }else{                        $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);// 普通的也就是个数组映射了                    }                }elseif('bind' == $exp ){ // 使用表达式                    $whereStr .= $key.' = :'.$val[1]; // 特殊表达式                }elseif('exp' == $exp ){ // 使用表达式                    $whereStr .= $key.' '.$val[1];// 自己写的表达式                }elseif(preg_match('/^(notin|not in|in)$/',$exp)){ // IN 运算                    if(isset($val[2]) && 'exp'==$val[2]) {                        $whereStr .= $key.' '.$this->exp[$exp].' '.$val[1];// 也是个神奇的转换                    }else{                        if(is_string($val[1])) { // 直接 把字符串 转换成为数组                            $val[1] =  explode(',',$val[1]);                        }                        $zone      =   implode(',',$this->parseValue($val[1])); // 过滤一下                        $whereStr .= $key.' '.$this->exp[$exp].' ('.$zone.')'; // 然后在转化回去                    }                }elseif(preg_match('/^(notbetween|not between|between)$/',$exp)){ // BETWEEN运算                    $data = is_string($val[1])? explode(',',$val[1]):$val[1];                    $whereStr .=  $key.' '.$this->exp[$exp].' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]);                }else{// 其它的传入都不正确                    E(L('_EXPRESS_ERROR_').':'.$val[0]);                }            }else {// 非字符串表达式的 怎么玩呢                $count = count($val);                // 获取逻辑规则                $rule  = isset($val[$count-1]) ? (is_array($val[$count-1]) ? strtoupper($val[$count-1][0]) : strtoupper($val[$count-1]) ) : '' ;                if(in_array($rule,array('AND','OR','XOR'))) {                    $count  = $count -1;                }else{                    $rule   = 'AND';                }                // 遍历全部数据                for($i=0;$i<$count;$i++) {                    $data = is_array($val[$i])?$val[$i][1]:$val[$i];                    if('exp'==strtolower($val[$i][0])) {                        $whereStr .= $key.' '.$data.' '.$rule.' ';                    }else{                        $whereStr .= $this->parseWhereItem($key,$val[$i]).' '.$rule.' ';                    }                }                $whereStr = '( '.substr($whereStr,0,-4).' )';            }        }else {            //对字符串类型字段采用模糊匹配            // 如果你什么都不写,就写个数值的话,默认就读取你的 参数 进行最大的模糊匹配            $likeFields   =   $this->config['db_like_fields'];            if($likeFields && preg_match('/^('.$likeFields.')$/i',$key)) {                $whereStr .= $key.' LIKE '.$this->parseValue('%'.$val.'%');            }else {                $whereStr .= $key.' = '.$this->parseValue($val);            }        }        return $whereStr;    }    /**     * 特殊条件分析     * @access protected     * @param string $key     * @param mixed $val     * @return string     */    protected function parseThinkWhere($key,$val) {        $whereStr   = '';        switch($key) {            case '_string':                // 字符串模式查询条件                $whereStr = $val;                break;            case '_complex':                // 复合查询条件                $whereStr = substr($this->parseWhere($val),6);                break;            case '_query':                // 字符串模式查询条件                parse_str($val,$where);                if(isset($where['_logic'])) {                    $op   =  ' '.strtoupper($where['_logic']).' ';                    unset($where['_logic']);                }else{                    $op   =  ' AND ';                }                $array   =  array();                foreach ($where as $field=>$data)                    $array[] = $this->parseKey($field).' = '.$this->parseValue($data);                $whereStr   = implode($op,$array);                break;        }        return '( '.$whereStr.' )';    }    /**     * limit分析     * @access protected     * @param mixed $lmit     * @return string     * 这个太容易了     */    protected function parseLimit($limit) {        return !empty($limit)?   ' LIMIT '.$limit.' ':'';    }    /**     * join分析     * @access protected     * @param mixed $join     * @return string     * 一个组合而已了 组合 开始     */    protected function parseJoin($join) {        $joinStr = '';        if(!empty($join)) {// 如果不为空            $joinStr    =   ' '.implode(' ',$join).' ';        }        return $joinStr;    }    /**     * order分析     * @access protected     * @param mixed $order     * @return string     *  SELECT * FROM t1 WHERE key_part1=1 ORDER BY key_part1 DESC, key_part2 DESC;     */    protected function parseOrder($order) {        if(is_array($order)) {// key 一般作为 fields            $array   =  array();            foreach ($order as $key=>$val){                if(is_numeric($key)) {                    $array[] =  $this->parseKey($val);                }else{                    $array[] =  $this->parseKey($key).' '.$val;                }            }            $order   =  implode(',',$array); // 基础组合,然后 组件 新的位置        }        return !empty($order)?  ' ORDER BY '.$order:'';    }    /**     * group分析     * @access protected     * @param mixed $group     * @return string     * 就是个 封装的 包装而已了     */    protected function parseGroup($group) {        return !empty($group)? ' GROUP BY '.$group:'';    }    /**     * having分析     * @access protected     * @param string $having     * @return string     * 同上,无语中 ............     */    protected function parseHaving($having) {        return  !empty($having)?   ' HAVING '.$having:'';    }    /**     * comment分析     * @access protected     * @param string $comment     * @return string     *  注释都解析,还是可以了     */    protected function parseComment($comment) {        return  !empty($comment)?   ' /* '.$comment.' */':'';    }    /**     * distinct分析     * @access protected     * @param mixed $distinct     * @return string     * DISTINCT  去掉重复的数据     * select distinct name from table     */    protected function parseDistinct($distinct) {        return !empty($distinct)?   ' DISTINCT ' :'';    }    /**     * union分析     * @access protected     * @param mixed $union     * @return string     */    protected function parseUnion($union) {        if(empty($union)) return ''; // 没有的话,你解析个什么呢        if(isset($union['_all'])) { // 如果是 all            $str  =   'UNION ALL ';            unset($union['_all']);        }else{            $str  =   'UNION ';        }        /**         * union 对两个结果集进行并集操作,重复数据只显示一次        Union All,对两个结果集进行并集操作,重复数据全部显示         */        // 上述准备完成,准备清空        foreach ($union as $u){            $sql[] = $str.(is_array($u)?$this->buildSelectSql($u):$u);        }// 牛叉啊,居然还是个组合,嘿嘿        return implode(' ',$sql);    }    /**     * 参数绑定分析     * @access protected     * @param array $bind     * @return array     * 还不如直接用这个 函数呢,弄的感觉很是高大上的样子。     */    protected function parseBind($bind){        $this->bind   =   array_merge($this->bind,$bind);    }    /**     * index分析,可在操作链中指定需要强制使用的索引     * @access protected     * @param mixed $index     * @return string     */    protected function parseForce($index) {        if(empty($index)) return '';        if(is_array($index)) $index = join(",", $index); //join — 别名 implode()        return sprintf(" FORCE INDEX ( %s ) ", $index); // 这个是个 强制索引,牛叉    }    /**     * ON DUPLICATE KEY UPDATE 分析     * @access protected     * @param mixed $duplicate     * @return string     * 空白啊,这个彻底的忽悠啊     */    protected function parseDuplicate($duplicate){        return '';    }//////////////////////////////////////////////////////////////////    /**     * 获取最近一次查询的sql语句     * @param string $model  模型名     * @access public     * @return string     * 容易的先过一下,哈哈哈 , 多语句存储     */    public function getLastSql($model='') {        return $model?$this->modelSql[$model]:$this->queryStr;    }    /**     * 获取最近插入的ID     * @access public     * @return string     * 简单封装 返回 跟最开始时候的 get 差不多的样子     */    public function getLastInsID() {        return $this->lastInsID;    }    /**     * 获取最近的错误信息     * @access public     * @return string     * 同上,无语中.............     */    public function getError() {        return $this->error;    }    /**     * SQL指令安全过滤     * @access public     * @param string $str  SQL字符串     * @return string     * 就这个也能过滤吗,估计靠谱吧     */    public function escapeString($str) {        return addslashes($str); // addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。    }    /**     * 设置当前操作模型     * @access public     * @param string $model  模型名     * @return void     * 同上了.........     */    public function setModel($model){        $this->model =  $model;    }    /**     * 数据库调试 记录当前SQL     * @access protected     * @param boolean $start  调试开始标记 true 开始 false 结束     * 调试 其实,就是个 记录运行,跟输出     */    protected function debug($start) {        if($this->config['debug']) {// 开启数据库调试模式            if($start) {                G('queryStartTime'); // 开始记录            }else{                $this->modelSql[$this->model]   =  $this->queryStr;                //$this->model  =   '_think_';                // 记录操作结束时间                G('queryEndTime'); // 记录时间                trace($this->queryStr.' [ RunTime:'.G('queryStartTime','queryEndTime').'s ]','','SQL');                // 记录到日志信息 也可以输出到页面            }        }    }    /**     * 初始化数据库连接     * @access protected     * @param boolean $master 主服务器     * @return void     * 数据库的连接  分布式连接 跟单独的连接     */    protected function initConnect($master=true) {        if(!empty($this->config['deploy']))            // 采用分布式数据库            $this->_linkID = $this->multiConnect($master);        else            // 默认单数据库            if ( !$this->_linkID ) $this->_linkID = $this->connect();    }    /**     * 析构方法     * @access public     * 删除 记录     */    public function __destruct() {        // 释放查询        if ($this->PDOStatement){            $this->free();        }        // 关闭连接        $this->close();    }// 今日继续,上午也没录成课程,全部都是答疑了    /**     * 插入记录     * @access public     * @param mixed $data 数据     * @param array $options 参数表达式     * @param boolean $replace 是否replace     * @return false | integer     */    public function insert($data,$options=array(),$replace=false) {        $values  =  $fields    = array(); // 清空准备仓库        $this->model  =   $options['model']; // 准备当前模式        $this->parseBind(!empty($options['bind'])?$options['bind']:array());// 参数绑定准备        foreach ($data as $key=>$val){// 对传入的数据进行处理            if(is_array($val) && 'exp' == $val[0]){ // 如果数值为数组,并且 说明是表达式                $fields[]   =  $this->parseKey($key); // key 处理                $values[]   =  $val[1];// val 直接用了,危险啊,哥哥,都不处理一下呢            }elseif(is_null($val)){// 单独处理个NULL                $fields[]   =   $this->parseKey($key);                $values[]   =   'NULL';            }elseif(is_scalar($val)) { // 过滤非标量数据                $fields[]   =   $this->parseKey($key);// 先处理个 key                if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){                    $values[]   =   $this->parseValue($val);                }else{                    $name       =   count($this->bind);                    $values[]   =   ':'.$name;                    $this->bindParam($name,$val);                }                // 特殊处理,表示都是外包的黑盒子,没怎么看懂,这个怎么办呢?            }        }        // 兼容数字传入方式        $replace= (is_numeric($replace) && $replace>0)?true:$replace;        // 其实这个还兼容了,一个不是很常用的 sql ,反正我是这样信的        $sql    = (true===$replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'.$this->parseDuplicate($replace);        // 格外处理个评论        $sql    .= $this->parseComment(!empty($options['comment'])?$options['comment']:'');        // 返回执行结果        return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);    }    // 新的记录    /**     * 批量插入记录     * @access public     * @param mixed $dataSet 数据集     * @param array $options 参数表达式     * @param boolean $replace 是否replace     * @return false | integer     */    public function insertAll($dataSet,$options=array(),$replace=false) {        $values  =  array();// 仓库 临时的 仓库        $this->model  =   $options['model']; // 选项里面的 连接模型        //  protected $model      = '_think_';// 所属模型        if(!is_array($dataSet[0])) return false;// 如果插入的数据里面 什么都没有,那弄什么呢?        $this->parseBind(!empty($options['bind'])?$options['bind']:array());// 绑定了一个我不知道的参数        $fields =   array_map(array($this,'parseKey'),array_keys($dataSet[0])); // 类内部 传递参数        foreach ($dataSet as $data){ // 就是个 data to sql 数组 到数据库            $value   =  array();// 遍历数据 临时 子仓库            foreach ($data as $key=>$val){                if(is_array($val) && 'exp' == $val[0]){// 表达式                    $value[]   =    $val[1];                }elseif(is_null($val)){// null 重新准备                    $value[]   =   'NULL';                }elseif(is_scalar($val)){ // 非标量 数据                    if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){                        $value[]   =   $this->parseValue($val);                    }else{                        $name       =   count($this->bind); // 另外的一种形式的绑定                        $value[]   =   ':'.$name;                        $this->bindParam($name,$val);// 解析参数                    }                }            }            $values[]    = 'SELECT '.implode(',', $value);        }        // 批量插入语句,不知道,是否可以正常使用        $sql   =  'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') '.implode(' UNION ALL ',$values);        $sql   .= $this->parseComment(!empty($options['comment'])?$options['comment']:'');// 处理评论        return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);// 执行语句    }    /**     * 通过Select方式插入记录     * @access public     * @param string $fields 要插入的数据表字段名     * @param string $table 要插入的数据表名     * @param array $option  查询数据参数     * @return false | integer     */    public function selectInsert($fields,$table,$options=array()) {        $this->model  =   $options['model'];// 模型管理        $this->parseBind(!empty($options['bind'])?$options['bind']:array());// 绑定参数        if(is_string($fields))   $fields    = explode(',',$fields); // 处理字段        array_walk($fields, array($this, 'parseKey')); // 敢告诉我 这个 walk 跟 那个 有什么区别吗啊,哈哈        $sql   =    'INSERT INTO '.$this->parseTable($table).' ('.implode(',', $fields).') ';// 插入数据        $sql   .= $this->buildSelectSql($options);// 开始 创建语句        return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);// 执行 sql 语句    }    /**     * 更新记录     * @access public     * @param mixed $data 数据     * @param array $options 表达式     * @return false | integer     */    public function update($data,$options) {        $this->model  =   $options['model'];        $this->parseBind(!empty($options['bind'])?$options['bind']:array());        $table  =   $this->parseTable($options['table']);        $sql   = 'UPDATE ' . $table . $this->parseSet($data); // 一样的调调,我懂了        if(strpos($table,',')){// 多表更新支持JOIN操作  多表 的 jion 操作            $sql .= $this->parseJoin(!empty($options['join'])?$options['join']:''); // 外包        }        $sql .= $this->parseWhere(!empty($options['where'])?$options['where']:''); // 外包        if(!strpos($table,',')){            //  单表更新支持order和lmit            $sql   .=  $this->parseOrder(!empty($options['order'])?$options['order']:'')                .$this->parseLimit(!empty($options['limit'])?$options['limit']:'');        } //UPDATE channel_config set is_adam_pub=1 LIMIT 5607;        // 靠谱 重大发现啊        //UPDATE  `my_to_do_list`.`users` SET  `email` =  'guanyu@888.com1' WHERE  `users`.`id` =3;        $sql .=   $this->parseComment(!empty($options['comment'])?$options['comment']:'');        return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);// 执行sql 语句    }// 29 开始    /**     * 删除记录     * @access public     * @param array $options 表达式     * @return false | integer     */    public function delete($options=array()) {        $this->model  =   $options['model'];        $this->parseBind(!empty($options['bind'])?$options['bind']:array());        $table  =   $this->parseTable($options['table']);        $sql    =   'DELETE FROM '.$table;// 删除 问题        if(strpos($table,',')){// 多表删除支持USING和JOIN操作            if(!empty($options['using'])){// 各种外包啊                $sql .= ' USING '.$this->parseTable($options['using']).' ';            }            $sql .= $this->parseJoin(!empty($options['join'])?$options['join']:'');        }        $sql .= $this->parseWhere(!empty($options['where'])?$options['where']:'');        if(!strpos($table,',')){ // 分条件外包,牛叉            // 单表删除支持order和limit            $sql .= $this->parseOrder(!empty($options['order'])?$options['order']:'')                .$this->parseLimit(!empty($options['limit'])?$options['limit']:'');        }        $sql .=   $this->parseComment(!empty($options['comment'])?$options['comment']:'');        return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);    }    // 总结,一个外包公司    /**     * 查找记录     * @access public     * @param array $options 表达式     * @return mixed     * 这个倒是很干净利落     */    public function select($options=array()) {        $this->model  =   $options['model'];        $this->parseBind(!empty($options['bind'])?$options['bind']:array());        $sql    = $this->buildSelectSql($options);        $result   = $this->query($sql,!empty($options['fetch_sql']) ? true : false);        return $result;    }///////////////////////////////////////////////////////////////////////////    /**     * 生成查询SQL     * @access public     * @param array $options 表达式     * @return string     */    public function buildSelectSql($options=array()) {        if(isset($options['page'])) { // 如果有 分页的效果            // 根据页数计算limit            list($page,$listRows)   =   $options['page'];            $page    =  $page>0 ? $page : 1;// 处理默认数据            $listRows=  $listRows>0 ? $listRows : (is_numeric($options['limit'])?$options['limit']:20);            $offset  =  $listRows*($page-1);// 偏移量            $options['limit'] =  $offset.','.$listRows; // 生成限制 sql 语句        }        $sql  =   $this->parseSql($this->selectSql,$options);// 解析字符串        return $sql;    }    //    /**     * 替换SQL语句中表达式     * @access public     * @param array $options 表达式     * @return string     * 看来这个是总外包     */    public function parseSql($sql,$options=array()){        $sql   = str_replace(            array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%LOCK%','%COMMENT%','%FORCE%'),            array(                $this->parseTable($options['table']),                $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),                $this->parseField(!empty($options['field'])?$options['field']:'*'),                $this->parseJoin(!empty($options['join'])?$options['join']:''),                $this->parseWhere(!empty($options['where'])?$options['where']:''),                $this->parseGroup(!empty($options['group'])?$options['group']:''),                $this->parseHaving(!empty($options['having'])?$options['having']:''),                $this->parseOrder(!empty($options['order'])?$options['order']:''),                $this->parseLimit(!empty($options['limit'])?$options['limit']:''),                $this->parseUnion(!empty($options['union'])?$options['union']:''),                $this->parseLock(isset($options['lock'])?$options['lock']:false),                $this->parseComment(!empty($options['comment'])?$options['comment']:''),                $this->parseForce(!empty($options['force'])?$options['force']:'')            ),$sql);        return $sql;    }    /**     * 连接分布式服务器     * @access protected     * @param boolean $master 主服务器     * @return void     */    protected function multiConnect($master=false) {        // 分布式数据库配置解析        $_config['username']    =   explode(',',$this->config['username']);        $_config['password']    =   explode(',',$this->config['password']);        $_config['hostname']    =   explode(',',$this->config['hostname']);        $_config['hostport']    =   explode(',',$this->config['hostport']);        $_config['database']    =   explode(',',$this->config['database']);        $_config['dsn']         =   explode(',',$this->config['dsn']);        $_config['charset']     =   explode(',',$this->config['charset']);        $m     =   floor(mt_rand(0,$this->config['master_num']-1));        // 随机数据库的 读取        // 数据库读写是否分离        if($this->config['rw_separate']){            // 主从式采用读写分离            if($master)                // 主服务器写入                $r  =   $m;            else{                if(is_numeric($this->config['slave_no'])) {// 指定服务器读                    $r = $this->config['slave_no'];                }else{                    // 读操作连接从服务器                    $r = floor(mt_rand($this->config['master_num'],count($_config['hostname'])-1));   // 每次随机连接的数据库                }            }        }else{            // 读写操作不区分服务器            $r = floor(mt_rand(0,count($_config['hostname'])-1));   // 每次随机连接的数据库        }        if($m != $r ){            $db_master  =   array(                'username'  =>  isset($_config['username'][$m])?$_config['username'][$m]:$_config['username'][0],                'password'  =>  isset($_config['password'][$m])?$_config['password'][$m]:$_config['password'][0],                'hostname'  =>  isset($_config['hostname'][$m])?$_config['hostname'][$m]:$_config['hostname'][0],                'hostport'  =>  isset($_config['hostport'][$m])?$_config['hostport'][$m]:$_config['hostport'][0],                'database'  =>  isset($_config['database'][$m])?$_config['database'][$m]:$_config['database'][0],                'dsn'       =>  isset($_config['dsn'][$m])?$_config['dsn'][$m]:$_config['dsn'][0],                'charset'   =>  isset($_config['charset'][$m])?$_config['charset'][$m]:$_config['charset'][0],            );        }        $db_config = array(            'username'  =>  isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],            'password'  =>  isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],            'hostname'  =>  isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],            'hostport'  =>  isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],            'database'  =>  isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],            'dsn'       =>  isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],            'charset'   =>  isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0],        );        return $this->connect($db_config,$r,$r == $m ? false : $db_master);    }    // 总结,其实貌似神秘的 没有什么神秘的地方?    // 就是更多了 那个 对应数据的一个转换封装,其它的 什么也没了    // 哦 忘了上面的那个 sql 的 分布式,跟后宫翻牌子是的,哈哈// 结束了}
阅读全文
0 0
原创粉丝点击