改进数据库驱动

This commit is contained in:
thinkphp
2015-01-29 14:31:45 +08:00
parent 55adc28ac0
commit 6ecc2963f1
2 changed files with 397 additions and 166 deletions

View File

@@ -56,7 +56,7 @@ abstract class Driver {
// 数据库表达式 // 数据库表达式
protected $comparison = ['eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN']; protected $comparison = ['eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN'];
// 查询表达式 // 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%'; protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';
// 查询次数 // 查询次数
protected $queryTimes = 0; protected $queryTimes = 0;
// 执行次数 // 执行次数
@@ -78,7 +78,9 @@ abstract class Driver {
public function __construct($config=''){ public function __construct($config=''){
if(!empty($config)) { if(!empty($config)) {
$this->config = array_merge($this->config,$config); $this->config = array_merge($this->config,$config);
$this->config['params'] = $this->options+$this->config['params']; if(is_array($this->config['params'])){
$this->options = $this->config['params'] + $this->options;
}
} }
} }
@@ -86,16 +88,21 @@ abstract class Driver {
* 连接数据库方法 * 连接数据库方法
* @access public * @access public
*/ */
public function connect($config='',$linkNum=0) { public function connect($config='',$linkNum=0,$autoConnection=false) {
if ( !isset($this->linkID[$linkNum]) ) { if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config; if(empty($config)) $config = $this->config;
try{ try{
if(empty($config['dsn'])) { if(empty($config['dsn'])) {
$config['dsn'] = $this->parseDsn($config); $config['dsn'] = $this->parseDsn($config);
} }
$this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$config['params']); $this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$this->options);
}catch (\PDOException $e) { }catch (\PDOException $e) {
E($e->getMessage()); if($autoConnection){
Log::record($e->getMessage(),'ERR');
return $this->connect($autoConnection,$linkNum);
}elseif($config['debug']){
E($e->getMessage());
}
} }
} }
return $this->linkID[$linkNum]; return $this->linkID[$linkNum];
@@ -121,15 +128,19 @@ abstract class Driver {
* 执行查询 返回数据集 * 执行查询 返回数据集
* @access public * @access public
* @param string $str sql指令 * @param string $str sql指令
* @param array $bind 参数绑定 * @param boolean $fetchSql 不执行只是获取SQL
* @return mixed * @return mixed
*/ */
public function query($str,$bind=[]) { public function query($str,$fetchSql=false) {
$this->initConnect(false); $this->initConnect(false);
if ( !$this->_linkID ) return false; if ( !$this->_linkID ) return false;
$this->queryStr = $str; $this->queryStr = $str;
if(!empty($bind)){ if(!empty($this->bind)){
$this->queryStr .= '[ '.print_r($bind,true).' ]'; $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(); if ( !empty($this->PDOStatement) ) $this->free();
@@ -137,15 +148,18 @@ abstract class Driver {
// 调试开始 // 调试开始
$this->debug(true); $this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str); $this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement) if(false === $this->PDOStatement){
E($this->error()); $this->error();
foreach ($bind as $key => $val) { return false;
}
foreach ($this->bind as $key => $val) {
if(is_array($val)){ if(is_array($val)){
$this->PDOStatement->bindValue($key, $val[0], $val[1]); $this->PDOStatement->bindValue($key, $val[0], $val[1]);
}else{ }else{
$this->PDOStatement->bindValue($key, $val); $this->PDOStatement->bindValue($key, $val);
} }
} }
$this->bind = [];
$result = $this->PDOStatement->execute(); $result = $this->PDOStatement->execute();
// 调试结束 // 调试结束
$this->debug(false); $this->debug(false);
@@ -161,33 +175,39 @@ abstract class Driver {
* 执行语句 * 执行语句
* @access public * @access public
* @param string $str sql指令 * @param string $str sql指令
* @param array $bind 参数绑定 * @param boolean $fetchSql 不执行只是获取SQL
* @return integer * @return integer
*/ */
public function execute($str,$bind=[]) { public function execute($str,$fetchSql=false) {
$this->initConnect(true); $this->initConnect(true);
if ( !$this->_linkID ) return false; if ( !$this->_linkID ) return false;
$this->queryStr = $str; $this->queryStr = $str;
if(!empty($bind)){ if(!empty($this->bind)){
$this->queryStr .= '[ '.print_r($bind,true).' ]'; $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(); if ( !empty($this->PDOStatement) ) $this->free();
$this->executeTimes++; $this->executeTimes++;
// 记录开始执行时间 // 记录开始执行时间
$this->debug(true); $this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str); $this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement) { if(false === $this->PDOStatement) {
E($this->error()); $this->error();
return false;
} }
foreach ($bind as $key => $val) { foreach ($this->bind as $key => $val) {
if(is_array($val)){ if(is_array($val)){
$this->PDOStatement->bindValue($key, $val[0], $val[1]); $this->PDOStatement->bindValue($key, $val[0], $val[1]);
}else{ }else{
$this->PDOStatement->bindValue($key, $val); $this->PDOStatement->bindValue($key, $val);
} }
} }
$result = $this->PDOStatement->execute(); $this->bind = [];
$result = $this->PDOStatement->execute();
$this->debug(false); $this->debug(false);
if ( false === $result) { if ( false === $result) {
$this->error(); $this->error();
@@ -332,13 +352,17 @@ abstract class Driver {
*/ */
protected function parseSet($data) { protected function parseSet($data) {
foreach ($data as $key=>$val){ foreach ($data as $key=>$val){
if(is_scalar($val)) {// 过滤非标量数据 if(is_array($val) && 'exp' == $val[0]){
if(0===strpos($val,':')){ $set[] = $this->parseKey($key).'='.$val[1];
}elseif(is_null($val)){
$set[] = $this->parseKey($key).'=NULL';
}elseif(is_scalar($val)) {// 过滤非标量数据
if(0===strpos($val,':') && in_array($val,array_keys($this->bind)) ){
$set[] = $this->parseKey($key).'='.$this->escapeString($val); $set[] = $this->parseKey($key).'='.$this->escapeString($val);
}else{ }else{
$name = count($this->bind); $name = count($this->bind);
$set[] = $this->parseKey($key).'=:'.$name; $set[] = $this->parseKey($key).'=:'.$name;
$this->bindParam($name,$val); $this->bindParam($name,$val);
} }
} }
} }
@@ -374,7 +398,7 @@ abstract class Driver {
*/ */
protected function parseValue($value) { protected function parseValue($value) {
if(is_string($value)) { if(is_string($value)) {
$value = strpos($value,':') === 0 ? $this->escapeString($value) : '\''.$this->escapeString($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'){ }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
$value = $this->escapeString($value[1]); $value = $this->escapeString($value[1]);
}elseif(is_array($value)) { }elseif(is_array($value)) {
@@ -453,7 +477,7 @@ abstract class Driver {
$whereStr = $where; $whereStr = $where;
}else{ // 使用数组表达式 }else{ // 使用数组表达式
$operate = isset($where['_logic'])?strtoupper($where['_logic']):''; $operate = isset($where['_logic'])?strtoupper($where['_logic']):'';
if(in_array($operate,['AND','OR','XOR'])){ if(in_array($operate,array('AND','OR','XOR'))){
// 定义逻辑运算规则 例如 OR XOR AND NOT // 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' '.$operate.' '; $operate = ' '.$operate.' ';
unset($where['_logic']); unset($where['_logic']);
@@ -462,39 +486,41 @@ abstract class Driver {
$operate = ' AND '; $operate = ' AND ';
} }
foreach ($where as $key=>$val){ foreach ($where as $key=>$val){
$whereStr .= '( '; if(is_numeric($key)){
$key = '_complex';
}
if(0===strpos($key,'_')) { if(0===strpos($key,'_')) {
// 解析特殊条件表达式 // 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val); $whereStr .= $this->parseThinkWhere($key,$val);
}else{ }else{
// 查询字段的安全过滤 // 查询字段的安全过滤
if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){ // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
E(L('_EXPRESS_ERROR_').':'.$key); // E(L('_EXPRESS_ERROR_').':'.$key);
} // }
// 多条件支持 // 多条件支持
$multi = is_array($val) && isset($val['_multi']); $multi = is_array($val) && isset($val['_multi']);
$key = trim($key); $key = trim($key);
if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段 if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段
$array = explode('|',$key); $array = explode('|',$key);
$str = []; $str = array();
foreach ($array as $m=>$k){ foreach ($array as $m=>$k){
$v = $multi?$val[$m]:$val; $v = $multi?$val[$m]:$val;
$str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')'; $str[] = $this->parseWhereItem($this->parseKey($k),$v);
} }
$whereStr .= implode(' OR ',$str); $whereStr .= '( '.implode(' OR ',$str).' )';
}elseif(strpos($key,'&')){ }elseif(strpos($key,'&')){
$array = explode('&',$key); $array = explode('&',$key);
$str = []; $str = array();
foreach ($array as $m=>$k){ foreach ($array as $m=>$k){
$v = $multi?$val[$m]:$val; $v = $multi?$val[$m]:$val;
$str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')'; $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
} }
$whereStr .= implode(' AND ',$str); $whereStr .= '( '.implode(' AND ',$str).' )';
}else{ }else{
$whereStr .= $this->parseWhereItem($this->parseKey($key),$val); $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
} }
} }
$whereStr .= ' )'.$operate; $whereStr .= $operate;
} }
$whereStr = substr($whereStr,0,-strlen($operate)); $whereStr = substr($whereStr,0,-strlen($operate));
} }
@@ -506,46 +532,46 @@ abstract class Driver {
$whereStr = ''; $whereStr = '';
if(is_array($val)) { if(is_array($val)) {
if(is_string($val[0])) { if(is_string($val[0])) {
if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT)$/i',$val[0])) { // 比较运算 $exp = strtolower($val[0]);
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]); if(preg_match('/^(eq|neq|gt|egt|lt|elt)$/',$exp)) { // 比较运算
}elseif(preg_match('/^(NOTLIKE|LIKE)$/i',$val[0])){// 模糊查找 $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);
}elseif(preg_match('/^(notlike|like)$/',$exp)){// 模糊查找
if(is_array($val[1])) { if(is_array($val[1])) {
$likeLogic = isset($val[2])?strtoupper($val[2]):'OR'; $likeLogic = isset($val[2])?strtoupper($val[2]):'OR';
if(in_array($likeLogic,['AND','OR','XOR'])){ if(in_array($likeLogic,array('AND','OR','XOR'))){
$likeStr = $this->comparison[strtolower($val[0])]; $like = array();
$like = [];
foreach ($val[1] as $item){ foreach ($val[1] as $item){
$like[] = $key.' '.$likeStr.' '.$this->parseValue($item); $like[] = $key.' '.$this->exp[$exp].' '.$this->parseValue($item);
} }
$whereStr .= '('.implode(' '.$likeLogic.' ',$like).')'; $whereStr .= '('.implode(' '.$likeLogic.' ',$like).')';
} }
}else{ }else{
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]); $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($val[1]);
} }
}elseif('bind'==strtolower($val[0])){ // 使用表达式 }elseif('bind' == $exp ){ // 使用表达式
$whereStr .= ' ('.$key.' = :'.$val[1].') '; $whereStr .= $key.' = :'.$val[1];
}elseif('exp'==strtolower($val[0])){ // 使用表达式 }elseif('exp' == $exp ){ // 使用表达式
$whereStr .= ' ('.$key.' '.$val[1].') '; $whereStr .= $key.' '.$val[1];
}elseif(preg_match('/IN/i',$val[0])){ // IN 运算 }elseif(preg_match('/^(notin|not in|in)$/',$exp)){ // IN 运算
if(isset($val[2]) && 'exp'==$val[2]) { if(isset($val[2]) && 'exp'==$val[2]) {
$whereStr .= $key.' '.strtoupper($val[0]).' '.$val[1]; $whereStr .= $key.' '.$this->exp[$exp].' '.$val[1];
}else{ }else{
if(is_string($val[1])) { if(is_string($val[1])) {
$val[1] = explode(',',$val[1]); $val[1] = explode(',',$val[1]);
} }
$zone = implode(',',$this->parseValue($val[1])); $zone = implode(',',$this->parseValue($val[1]));
$whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')'; $whereStr .= $key.' '.$this->exp[$exp].' ('.$zone.')';
} }
}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算 }elseif(preg_match('/^(notbetween|not between|between)$/',$exp)){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1]; $data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= ' ('.$key.' '.strtoupper($val[0]).' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]).' )'; $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]);
}else{ }else{
E(L('_EXPRESS_ERROR_').':'.$val[0]); E(L('_EXPRESS_ERROR_').':'.$val[0]);
} }
}else { }else {
$count = count($val); $count = count($val);
$rule = isset($val[$count-1])?strtoupper($val[$count-1]):''; $rule = isset($val[$count-1]) ? (is_array($val[$count-1]) ? strtoupper($val[$count-1][0]) : strtoupper($val[$count-1]) ) : '' ;
if(in_array($rule,['AND','OR','XOR'])) { if(in_array($rule,array('AND','OR','XOR'))) {
$count = $count -1; $count = $count -1;
}else{ }else{
$rule = 'AND'; $rule = 'AND';
@@ -553,19 +579,18 @@ abstract class Driver {
for($i=0;$i<$count;$i++) { for($i=0;$i<$count;$i++) {
$data = is_array($val[$i])?$val[$i][1]:$val[$i]; $data = is_array($val[$i])?$val[$i][1]:$val[$i];
if('exp'==strtolower($val[$i][0])) { if('exp'==strtolower($val[$i][0])) {
$whereStr .= '('.$key.' '.$data.') '.$rule.' '; $whereStr .= $key.' '.$data.' '.$rule.' ';
}else{ }else{
$op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'='; $whereStr .= $this->parseWhereItem($key,$val[$i]).' '.$rule.' ';
$whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
} }
} }
$whereStr = substr($whereStr,0,-4); $whereStr = '( '.substr($whereStr,0,-4).' )';
} }
}else { }else {
//对字符串类型字段采用模糊匹配 //对字符串类型字段采用模糊匹配
if($this->config['db_like_fields'] && preg_match('/('.$this->config['db_like_fields'].')/i',$key)) { $likeFields = $this->config['db_like_fields'];
$val = '%'.$val.'%'; if($likeFields && preg_match('/^('.$likeFields.')$/i',$key)) {
$whereStr .= $key.' LIKE '.$this->parseValue($val); $whereStr .= $key.' LIKE '.$this->parseValue('%'.$val.'%');
}else { }else {
$whereStr .= $key.' = '.$this->parseValue($val); $whereStr .= $key.' = '.$this->parseValue($val);
} }
@@ -628,19 +653,8 @@ abstract class Driver {
protected function parseJoin($join) { protected function parseJoin($join) {
$joinStr = ''; $joinStr = '';
if(!empty($join)) { if(!empty($join)) {
if(is_array($join)) { $joinStr = ' '.implode(' ',$join).' ';
foreach ($join as $key=>$_join){
if(false !== stripos($_join,'JOIN'))
$joinStr .= ' '.$_join;
else
$joinStr .= ' LEFT JOIN ' .$_join;
}
}else{
$joinStr .= ' LEFT JOIN ' .$join;
}
} }
//将__TABLE_NAME__这样的字符串替换成正规的表名,并且带上前缀和后缀
$joinStr = preg_replace("/__([A-Z_-]+)__/esU",$this->config['prefix'].".strtolower('$1')",$joinStr);
return $joinStr; return $joinStr;
} }
@@ -732,9 +746,29 @@ abstract class Driver {
* @return array * @return array
*/ */
protected function parseBind($bind){ protected function parseBind($bind){
$bind = array_merge($this->bind,$bind); $this->bind = array_merge($this->bind,$bind);
$this->bind = []; }
return $bind;
/**
* index分析可在操作链中指定需要强制使用的索引
* @access protected
* @param mixed $index
* @return string
*/
protected function parseForce($index) {
if(empty($index)) return '';
if(is_array($index)) $index = join(",", $index);
return sprintf(" FORCE INDEX ( %s ) ", $index);
}
/**
* ON DUPLICATE KEY UPDATE 分析
* @access protected
* @param mixed $duplicate
* @return string
*/
protected function parseDuplicate($duplicate){
return '';
} }
/** /**
@@ -748,22 +782,68 @@ abstract class Driver {
public function insert($data,$options=[],$replace=false) { public function insert($data,$options=[],$replace=false) {
$values = $fields = []; $values = $fields = [];
$this->model = $options['model']; $this->model = $options['model'];
$this->parseBind(!empty($options['bind'])?$options['bind']:array());
foreach ($data as $key=>$val){ foreach ($data as $key=>$val){
if(is_scalar($val)) { // 过滤非标量数据 if(is_array($val) && 'exp' == $val[0]){
$fields[] = $this->parseKey($key);
$values[] = $val[1];
}elseif(is_null($val)){
$fields[] = $this->parseKey($key); $fields[] = $this->parseKey($key);
if(0===strpos($val,':')){ $values[] = 'NULL';
$values[] = $this->escapeString($val); }elseif(is_scalar($val)) { // 过滤非标量数据
$fields[] = $this->parseKey($key);
if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){
$values[] = $this->parseValue($val);
}else{ }else{
$name = count($this->bind); $name = count($this->bind);
$values[] = ':'.$name; $values[] = ':'.$name;
$this->bindParam($name,$val); $this->bindParam($name,$val);
} }
} }
} }
$sql = ($replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; // 兼容数字传入方式
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); $replace= (is_numeric($replace) && $replace>0)?true:$replace;
$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'];
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){
$value = array();
foreach ($data as $key=>$val){
if(is_array($val) && 'exp' == $val[0]){
$value[] = $val[1];
}elseif(is_null($val)){
$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']:''); $sql .= $this->parseComment(!empty($options['comment'])?$options['comment']:'');
return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[])); return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);
} }
/** /**
@@ -776,11 +856,12 @@ abstract class Driver {
*/ */
public function selectInsert($fields,$table,$options=[]) { public function selectInsert($fields,$table,$options=[]) {
$this->model = $options['model']; $this->model = $options['model'];
$this->parseBind(!empty($options['bind'])?$options['bind']:array());
if(is_string($fields)) $fields = explode(',',$fields); if(is_string($fields)) $fields = explode(',',$fields);
array_walk($fields, [$this, 'parseKey']); array_walk($fields, array($this, 'parseKey'));
$sql = 'INSERT INTO '.$this->parseTable($table).' ('.implode(',', $fields).') '; $sql = 'INSERT INTO '.$this->parseTable($table).' ('.implode(',', $fields).') ';
$sql .= $this->buildSelectSql($options); $sql .= $this->buildSelectSql($options);
return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[])); return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);
} }
/** /**
@@ -792,15 +873,20 @@ abstract class Driver {
*/ */
public function update($data,$options) { public function update($data,$options) {
$this->model = $options['model']; $this->model = $options['model'];
$sql = 'UPDATE ' $this->parseBind(!empty($options['bind'])?$options['bind']:array());
.$this->parseTable($options['table']) $table = $this->parseTable($options['table']);
.$this->parseSet($data) $sql = 'UPDATE ' . $table . $this->parseSet($data);
.$this->parseWhere(!empty($options['where'])?$options['where']:'') if(strpos($table,',')){// 多表更新支持JOIN操作
.$this->parseOrder(!empty($options['order'])?$options['order']:'') $sql .= $this->parseJoin(!empty($options['join'])?$options['join']:'');
.$this->parseLimit(!empty($options['limit'])?$options['limit']:'') }
.$this->parseLock(isset($options['lock'])?$options['lock']:false) $sql .= $this->parseWhere(!empty($options['where'])?$options['where']:'');
.$this->parseComment(!empty($options['comment'])?$options['comment']:''); if(!strpos($table,',')){
return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[])); // 单表更新支持order和lmit
$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);
} }
/** /**
@@ -811,14 +897,23 @@ abstract class Driver {
*/ */
public function delete($options=[]) { public function delete($options=[]) {
$this->model = $options['model']; $this->model = $options['model'];
$sql = 'DELETE FROM ' $this->parseBind(!empty($options['bind'])?$options['bind']:array());
.$this->parseTable($options['table']) $table = $this->parseTable($options['table']);
.$this->parseWhere(!empty($options['where'])?$options['where']:'') $sql = 'DELETE FROM '.$table;
.$this->parseOrder(!empty($options['order'])?$options['order']:'') if(strpos($table,',')){// 多表删除支持USING和JOIN操作
.$this->parseLimit(!empty($options['limit'])?$options['limit']:'') if(!empty($options['using'])){
.$this->parseLock(isset($options['lock'])?$options['lock']:false) $sql .= ' USING '.$this->parseTable($options['using']).' ';
.$this->parseComment(!empty($options['comment'])?$options['comment']:''); }
return $this->execute($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[])); $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);
} }
/** /**
@@ -829,19 +924,9 @@ abstract class Driver {
*/ */
public function select($options=[]) { public function select($options=[]) {
$this->model = $options['model']; $this->model = $options['model'];
$this->parseBind(!empty($options['bind'])?$options['bind']:array());
$sql = $this->buildSelectSql($options); $sql = $this->buildSelectSql($options);
$cache = isset($options['cache'])?$options['cache']:false; $result = $this->query($sql,!empty($options['fetch_sql']) ? true : false);
if($cache) { // 查询缓存检测
$key = is_string($cache['key'])?$cache['key']:md5($sql);
$value = S($key,'',$cache);
if(false !== $value) {
return $value;
}
}
$result = $this->query($sql,$this->parseBind(!empty($options['bind'])?$options['bind']:[]));
if($cache && false !== $result ) { // 查询缓存写入
S($key,$result,$cache);
}
return $result; return $result;
} }
@@ -854,18 +939,13 @@ abstract class Driver {
public function buildSelectSql($options=[]) { public function buildSelectSql($options=[]) {
if(isset($options['page'])) { if(isset($options['page'])) {
// 根据页数计算limit // 根据页数计算limit
if(strpos($options['page'],',')) { list($page,$listRows) = $options['page'];
list($page,$listRows) = explode(',',$options['page']); $page = $page>0 ? $page : 1;
}else{ $listRows= $listRows>0 ? $listRows : (is_numeric($options['limit'])?$options['limit']:20);
$page = $options['page']; $offset = $listRows*($page-1);
}
$page = $page?$page:1;
$listRows= isset($listRows)?$listRows:(is_numeric($options['limit'])?$options['limit']:20);
$offset = $listRows*((int)$page-1);
$options['limit'] = $offset.','.$listRows; $options['limit'] = $offset.','.$listRows;
} }
$sql = $this->parseSql($this->selectSql,$options); $sql = $this->parseSql($this->selectSql,$options);
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $sql; return $sql;
} }
@@ -877,7 +957,7 @@ abstract class Driver {
*/ */
public function parseSql($sql,$options=[]){ public function parseSql($sql,$options=[]){
$sql = str_replace( $sql = str_replace(
['%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%COMMENT%'], ['%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%LOCK%','%COMMENT%','%FORCE%'],
[ [
$this->parseTable($options['table']), $this->parseTable($options['table']),
$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false), $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
@@ -889,7 +969,9 @@ abstract class Driver {
$this->parseOrder(!empty($options['order'])?$options['order']:''), $this->parseOrder(!empty($options['order'])?$options['order']:''),
$this->parseLimit(!empty($options['limit'])?$options['limit']:''), $this->parseLimit(!empty($options['limit'])?$options['limit']:''),
$this->parseUnion(!empty($options['union'])?$options['union']:''), $this->parseUnion(!empty($options['union'])?$options['union']:''),
$this->parseComment(!empty($options['comment'])?$options['comment']:'') $this->parseLock(isset($options['lock'])?$options['lock']:false),
$this->parseComment(!empty($options['comment'])?$options['comment']:''),
$this->parseForce(!empty($options['force'])?$options['force']:'')
],$sql); ],$sql);
return $sql; return $sql;
} }
@@ -983,22 +1065,22 @@ abstract class Driver {
* @return void * @return void
*/ */
protected function multiConnect($master=false) { protected function multiConnect($master=false) {
static $_config = []; // 分布式数据库配置解析
if(empty($_config)) { $_config['username'] = explode(',',$this->config['username']);
// 缓存分布式数据库配置解析 $_config['password'] = explode(',',$this->config['password']);
$_config['username'] = explode(',',$$this->config['username']); $_config['hostname'] = explode(',',$this->config['hostname']);
$_config['password'] = explode(',',$$this->config['password']); $_config['hostport'] = explode(',',$this->config['hostport']);
$_config['hostname'] = explode(',',$$this->config['hostname']); $_config['database'] = explode(',',$this->config['database']);
$_config['hostport'] = explode(',',$$this->config['hostport']); $_config['dsn'] = explode(',',$this->config['dsn']);
$_config['database'] = explode(',',$$this->config['database']); $_config['charset'] = explode(',',$this->config['charset']);
$_config['dsn'] = explode(',',$$this->config['dsn']);
} $m = floor(mt_rand(0,$this->config['master_num']-1));
// 数据库读写是否分离 // 数据库读写是否分离
if($this->config['rw_separate']){ if($this->config['rw_separate']){
// 主从式采用读写分离 // 主从式采用读写分离
if($master) if($master)
// 主服务器写入 // 主服务器写入
$r = floor(mt_rand(0,$this->config['master_num']-1)); $r = $m;
else{ else{
if(is_numeric($this->config['slave_no'])) {// 指定服务器读 if(is_numeric($this->config['slave_no'])) {// 指定服务器读
$r = $this->config['slave_no']; $r = $this->config['slave_no'];
@@ -1011,15 +1093,28 @@ abstract class Driver {
// 读写操作不区分服务器 // 读写操作不区分服务器
$r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库 $r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库
} }
$db_config = [
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], 'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0], 'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0], 'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0], 'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0], 'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][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); );
return $this->connect($db_config,$r,$r == $m ? false : $db_master);
} }
/** /**

View File

@@ -218,6 +218,28 @@ class Model {
// 插入成功后的回调方法 // 插入成功后的回调方法
protected function _after_insert($data,$options) {} protected function _after_insert($data,$options) {}
public function addAll($dataList,$options=array(),$replace=false){
if(empty($dataList)) {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 数据处理
foreach ($dataList as $key=>$data){
$dataList[$key] = $this->_write_data($data);
}
// 分析表达式
$options = $this->_parseOptions($options);
// 写入数据到数据库
$result = $this->db->insertAll($dataList,$options,$replace);
if(false !== $result ) {
$insertId = $this->getLastInsID();
if($insertId) {
return $insertId;
}
}
return $result;
}
/** /**
* 保存数据 * 保存数据
* @access public * @access public
@@ -327,22 +349,50 @@ class Model {
$options = []; $options = [];
$options['where'] = $where; $options['where'] = $where;
}elseif(false === $options){ // 用于子查询 不查询只返回SQL }elseif(false === $options){ // 用于子查询 不查询只返回SQL
$options = []; return $this->buildSql();
// 分析表达式
$options = $this->_parseOptions($options);
return '( '.$this->db->buildSelectSql($options).' )';
} }
// 分析表达式 // 分析表达式
$options = $this->_parseOptions($options); $options = $this->_parseOptions($options);
// 判断查询缓存
if(isset($options['cache'])){
$cache = $options['cache'];
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
$data = S($key,'',$cache);
if(false !== $data){
return $data;
}
}
$resultSet = $this->db->select($options); $resultSet = $this->db->select($options);
if(false === $resultSet) { if(false === $resultSet) {
return false; return false;
} }
if(empty($resultSet)) { // 查询结果为空
return null; if(!empty($resultSet)) { // 有查询结果
if(is_string($resultSet)){
return $resultSet;
}
// 数据列表读取后的处理
$resultSet = $this->_read_datalist($resultSet);
if(isset($options['index'])){ // 对数据集进行索引
$index = explode(',',$options['index']);
foreach ($resultSet as $result){
$_key = $result[$index[0]];
if(isset($index[1]) && isset($result[$index[1]])){
$cols[$_key] = $result[$index[1]];
}else{
$cols[$_key] = $result;
}
}
$resultSet = $cols;
}
} }
// 数据列表读取后的处理
$resultSet = $this->_read_datalist($resultSet); if(isset($cache)){
S($key,$resultSet,$cache);
}
return $resultSet; return $resultSet;
} }
@@ -367,9 +417,7 @@ class Model {
* @return string * @return string
*/ */
public function buildSql($options=[]) { public function buildSql($options=[]) {
// 分析表达式 return '( '.$this->fetchSql(true)->select().' )';
$options = $this->_parseOptions($options);
return '( '.$this->db->buildSelectSql($options).' )';
} }
/** /**
@@ -381,8 +429,7 @@ class Model {
protected function _parseOptions($options=[]) { protected function _parseOptions($options=[]) {
if(is_array($options)) if(is_array($options))
$options = array_merge($this->options,$options); $options = array_merge($this->options,$options);
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = [];
if(!empty($options['alias'])) { if(!empty($options['alias'])) {
$options['table'] .= ' '.$options['alias']; $options['table'] .= ' '.$options['alias'];
@@ -411,6 +458,8 @@ class Model {
} }
} }
} }
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = [];
// 表达式过滤 // 表达式过滤
$this->_options_filter($options); $this->_options_filter($options);
return $options; return $options;
@@ -426,9 +475,11 @@ class Model {
* @return void * @return void
*/ */
protected function _parseType(&$data,$key) { protected function _parseType(&$data,$key) {
if(isset($this->fields['_type'][$key])) { if(!isset($this->options['bind'][':'.$key]) && isset($this->fields['_type'][$key])) {
$fieldType = strtolower($this->fields['_type'][$key]); $fieldType = strtolower($this->fields['_type'][$key]);
if(false === strpos($fieldType,'bigint') && false !== strpos($fieldType,'int')) { if(false !== strpos($fieldType,'enum')){
// 支持ENUM类型优先检测
}elseif(false === strpos($fieldType,'bigint') && false !== strpos($fieldType,'int')) {
$data[$key] = intval($data[$key]); $data[$key] = intval($data[$key]);
}elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
$data[$key] = floatval($data[$key]); $data[$key] = floatval($data[$key]);
@@ -454,6 +505,16 @@ class Model {
$options['limit'] = 1; $options['limit'] = 1;
// 分析表达式 // 分析表达式
$options = $this->_parseOptions($options); $options = $this->_parseOptions($options);
// 判断查询缓存
if(isset($options['cache'])){
$cache = $options['cache'];
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
$data = S($key,'',$cache);
if(false !== $data){
$this->data = $data;
return $data;
}
}
$resultSet = $this->db->select($options); $resultSet = $this->db->select($options);
if(false === $resultSet) { if(false === $resultSet) {
return false; return false;
@@ -461,10 +522,16 @@ class Model {
if(empty($resultSet)) {// 查询结果为空 if(empty($resultSet)) {// 查询结果为空
return null; return null;
} }
if(is_string($resultSet)){
return $resultSet;
}
// 数据处理 // 数据处理
$data = $this->_read_data($resultSet[0]); $data = $this->_read_data($resultSet[0]);
// 数据对象赋值 // 数据对象赋值
$this->data = $data; $this->data = $data;
if(isset($cache)){
S($key,$data,$cache);
}
return $this->data; return $this->data;
} }
@@ -734,13 +801,21 @@ class Model {
* 查询SQL组装 join * 查询SQL组装 join
* @access public * @access public
* @param mixed $join * @param mixed $join
* @param string $type JOIN类型
* @return Model * @return Model
*/ */
public function join($join) { public function join($join,$type='INNER') {
$prefix = $this->tablePrefix;
if(is_array($join)) { if(is_array($join)) {
foreach ($join as $key=>&$_join){
$_join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $_join);
$_join = false !== stripos($_join,'JOIN')? $_join : $type.' JOIN ' .$_join;
}
$this->options['join'] = $join; $this->options['join'] = $join;
}elseif(!empty($join)) { }elseif(!empty($join)) {
$this->options['join'][] = $join; //将__TABLE_NAME__字符串替换成带前缀的表名
$join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $join);
$this->options['join'][] = false !== stripos($join,'JOIN')? $join : $type.' JOIN '.$join;
} }
return $this; return $this;
} }
@@ -762,7 +837,9 @@ class Model {
} }
// 转换union表达式 // 转换union表达式
if(is_string($union) ) { if(is_string($union) ) {
$options = $union; $prefix = $this->tablePrefix;
//将__TABLE_NAME__字符串替换成带前缀的表名
$options = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $union);
}elseif(is_array($union)){ }elseif(is_array($union)){
if(isset($union[0])) { if(isset($union[0])) {
$this->options['union'] = array_merge($this->options['union'],$union); $this->options['union'] = array_merge($this->options['union'],$union);
@@ -786,6 +863,11 @@ class Model {
* @return Model * @return Model
*/ */
public function cache($key=true,$expire=null,$type=''){ public function cache($key=true,$expire=null,$type=''){
// 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
if(is_numeric($key) && is_null($expire)){
$expire = $key;
$key = true;
}
if(false !== $key) if(false !== $key)
$this->options['cache'] = ['key'=>$key,'expire'=>$expire,'type'=>$type]; $this->options['cache'] = ['key'=>$key,'expire'=>$expire,'type'=>$type];
return $this; return $this;
@@ -801,7 +883,7 @@ class Model {
public function field($field,$except=false){ public function field($field,$except=false){
if(true === $field) {// 获取全部字段 if(true === $field) {// 获取全部字段
$fields = $this->getDbFields(); $fields = $this->getDbFields();
$field = $fields?$fields:'*'; $field = $fields?:'*';
}elseif($except) {// 字段排除 }elseif($except) {// 字段排除
if(is_string($field)) { if(is_string($field)) {
$field = explode(',',$field); $field = explode(',',$field);
@@ -887,7 +969,10 @@ class Model {
* @return Model * @return Model
*/ */
public function limit($offset,$length=null){ public function limit($offset,$length=null){
$this->options['limit'] = is_null($length)?$offset:$offset.','.$length; if(is_null($length) && strpos($offset,',')){
list($offset,$length) = explode(',',$offset);
}
$this->options['limit'] = intval($offset).( $length? ','.intval($length) : '' );
return $this; return $this;
} }
@@ -899,7 +984,10 @@ class Model {
* @return Model * @return Model
*/ */
public function page($page,$listRows=null){ public function page($page,$listRows=null){
$this->options['page'] = is_null($listRows)?$page:$page.','.$listRows; if(is_null($listRows) && strpos($page,',')){
list($page,$listRows) = explode(',',$page);
}
$this->options['page'] = array(intval($page),intval($listRows));
return $this; return $this;
} }
@@ -910,7 +998,32 @@ class Model {
* @return Model * @return Model
*/ */
public function table($table){ public function table($table){
$this->options['table'] = $table; $prefix = $this->tablePrefix;
if(is_array($table)) {
$this->options['table'] = $table;
}elseif(!empty($table)) {
//将__TABLE_NAME__替换成带前缀的表名
$table = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $table);
$this->options['table'] = $table;
}
return $this;
}
/**
* USING支持 用于多表删除
* @access public
* @param mixed $using
* @return Model
*/
public function using($using){
$prefix = $this->tablePrefix;
if(is_array($using)) {
$this->options['using'] = $using;
}elseif(!empty($using)) {
//将__TABLE_NAME__替换成带前缀的表名
$using = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $using);
$this->options['using'] = $using;
}
return $this; return $this;
} }
@@ -992,13 +1105,25 @@ class Model {
} }
/** /**
* 指定参数绑定 * 参数绑定
* @access public * @access public
* @param array $bind 指定参数绑定 * @param string $key 参数名
* @param mixed $value 绑定的变量及绑定参数
* @return Model * @return Model
*/ */
public function bind($bind){ public function bind($key,$value=false) {
$this->options['bind'] = $bind; if(is_array($key)){
$this->options['bind'] = $key;
}else{
$num = func_num_args();
if($num>2){
$params = func_get_args();
array_shift($params);
$this->options['bind'][$key] = $params;
}else{
$this->options['bind'][$key] = $value;
}
}
return $this; return $this;
} }
@@ -1013,6 +1138,17 @@ class Model {
return $this; return $this;
} }
/**
* 获取执行的SQL语句
* @access public
* @param boolean $fetch 是否返回sql
* @return Model
*/
public function fetchSql($fetch){
$this->options['fetch_sql'] = $fetch;
return $this;
}
/** /**
* 设置字段映射 * 设置字段映射
* @access public * @access public