1165 lines
36 KiB
PHP
Executable File
1165 lines
36 KiB
PHP
Executable File
<?php
|
||
// +----------------------------------------------------------------------
|
||
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
|
||
// +----------------------------------------------------------------------
|
||
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
|
||
// +----------------------------------------------------------------------
|
||
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
|
||
// +----------------------------------------------------------------------
|
||
// | Author: liu21st <liu21st@gmail.com>
|
||
// +----------------------------------------------------------------------
|
||
|
||
namespace think\db;
|
||
|
||
use PDO;
|
||
use think\Exception;
|
||
|
||
abstract class Builder
|
||
{
|
||
// connection对象实例
|
||
protected $connection;
|
||
|
||
// 查询表达式映射
|
||
protected $exp = ['EQ' => '=', 'NEQ' => '<>', 'GT' => '>', 'EGT' => '>=', 'LT' => '<', 'ELT' => '<=', 'NOTLIKE' => 'NOT LIKE', 'NOTIN' => 'NOT IN', 'NOTBETWEEN' => 'NOT BETWEEN', 'NOTEXISTS' => 'NOT EXISTS', 'NOTNULL' => 'NOT NULL', 'NOTBETWEEN TIME' => 'NOT BETWEEN TIME'];
|
||
|
||
// 查询表达式解析
|
||
protected $parser = [
|
||
'parseCompare' => ['=', '<>', '>', '>=', '<', '<='],
|
||
'parseLike' => ['LIKE', 'NOT LIKE'],
|
||
'parseBetween' => ['NOT BETWEEN', 'BETWEEN'],
|
||
'parseIn' => ['NOT IN', 'IN'],
|
||
'parseExp' => ['EXP'],
|
||
'parseNull' => ['NOT NULL', 'NULL'],
|
||
'parseBetweenTime' => ['BETWEEN TIME', 'NOT BETWEEN TIME'],
|
||
'parseTime' => ['< TIME', '> TIME', '<= TIME', '>= TIME'],
|
||
'parseExists' => ['NOT EXISTS', 'EXISTS'],
|
||
'parseColumn' => ['COLUMN'],
|
||
];
|
||
|
||
// SQL表达式
|
||
protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%';
|
||
|
||
protected $insertSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%';
|
||
|
||
protected $insertAllSql = '%INSERT% INTO %TABLE% (%FIELD%) %DATA% %COMMENT%';
|
||
|
||
protected $updateSql = 'UPDATE %TABLE% SET %SET%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%';
|
||
|
||
protected $deleteSql = 'DELETE FROM %TABLE%%USING%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%';
|
||
|
||
/**
|
||
* 架构函数
|
||
* @access public
|
||
* @param Connection $connection 数据库连接对象实例
|
||
*/
|
||
public function __construct(Connection $connection)
|
||
{
|
||
$this->connection = $connection;
|
||
}
|
||
|
||
/**
|
||
* 获取当前的连接对象实例
|
||
* @access public
|
||
* @return Connection
|
||
*/
|
||
public function getConnection()
|
||
{
|
||
return $this->connection;
|
||
}
|
||
|
||
/**
|
||
* 注册查询表达式解析
|
||
* @access public
|
||
* @param string $name 解析方法
|
||
* @param array $parser 匹配表达式数据
|
||
* @return $this
|
||
*/
|
||
public function bindParser($name, $parser)
|
||
{
|
||
$this->parser[$name] = $parser;
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* 数据分析
|
||
* @access protected
|
||
* @param Query $query 查询对象
|
||
* @param array $data 数据
|
||
* @param array $fields 字段信息
|
||
* @param array $bind 参数绑定
|
||
* @return array
|
||
*/
|
||
protected function parseData(Query $query, $data = [], $fields = [], $bind = [])
|
||
{
|
||
if (empty($data)) {
|
||
return [];
|
||
}
|
||
|
||
$options = $query->getOptions();
|
||
|
||
// 获取绑定信息
|
||
if (empty($bind)) {
|
||
$bind = $this->connection->getFieldsBind($options['table']);
|
||
}
|
||
|
||
if (empty($fields)) {
|
||
if ('*' == $options['field']) {
|
||
$fields = array_keys($bind);
|
||
} else {
|
||
$fields = $options['field'];
|
||
}
|
||
}
|
||
|
||
$result = [];
|
||
|
||
foreach ($data as $key => $val) {
|
||
if ('*' != $options['field'] && !in_array($key, $fields, true)) {
|
||
continue;
|
||
}
|
||
|
||
$item = $this->parseKey($query, $key, true);
|
||
|
||
if ($val instanceof Expression) {
|
||
$result[$item] = $val->getValue();
|
||
continue;
|
||
} elseif (!is_scalar($val) && (in_array($key, (array) $query->getOptions('json')) || 'json' == $this->connection->getFieldsType($options['table'], $key))) {
|
||
$val = json_encode($val, JSON_UNESCAPED_UNICODE);
|
||
} elseif (is_object($val) && method_exists($val, '__toString')) {
|
||
// 对象数据写入
|
||
$val = $val->__toString();
|
||
}
|
||
|
||
if (false !== strpos($key, '->')) {
|
||
list($key, $name) = explode('->', $key);
|
||
$item = $this->parseKey($query, $key);
|
||
$result[$item] = 'json_set(' . $item . ', \'$.' . $name . '\', ' . $this->parseDataBind($query, $key, $val, $bind) . ')';
|
||
} elseif ('*' == $options['field'] && false === strpos($key, '.') && !in_array($key, $fields, true)) {
|
||
if ($options['strict']) {
|
||
throw new Exception('fields not exists:[' . $key . ']');
|
||
}
|
||
} elseif (is_null($val)) {
|
||
$result[$item] = 'NULL';
|
||
} elseif (is_array($val) && !empty($val)) {
|
||
switch (strtoupper($val[0])) {
|
||
case 'INC':
|
||
$result[$item] = $item . ' + ' . floatval($val[1]);
|
||
break;
|
||
case 'DEC':
|
||
$result[$item] = $item . ' - ' . floatval($val[1]);
|
||
break;
|
||
case 'EXP':
|
||
throw new Exception('not support data:[' . $val[0] . ']');
|
||
}
|
||
} elseif (is_scalar($val)) {
|
||
// 过滤非标量数据
|
||
$result[$item] = $this->parseDataBind($query, $key, $val, $bind);
|
||
}
|
||
}
|
||
|
||
return $result;
|
||
}
|
||
|
||
/**
|
||
* 数据绑定处理
|
||
* @access protected
|
||
* @param Query $query 查询对象
|
||
* @param string $key 字段名
|
||
* @param mixed $data 数据
|
||
* @param array $bind 绑定数据
|
||
* @return string
|
||
*/
|
||
protected function parseDataBind(Query $query, $key, $data, $bind = [])
|
||
{
|
||
if ($data instanceof Expression) {
|
||
return $data->getValue();
|
||
}
|
||
|
||
$name = $query->bind($data, isset($bind[$key]) ? $bind[$key] : PDO::PARAM_STR);
|
||
|
||
return ':' . $name;
|
||
}
|
||
|
||
/**
|
||
* 字段名分析
|
||
* @access public
|
||
* @param Query $query 查询对象
|
||
* @param mixed $key 字段名
|
||
* @param bool $strict 严格检测
|
||
* @return string
|
||
*/
|
||
public function parseKey(Query $query, $key, $strict = false)
|
||
{
|
||
return $key instanceof Expression ? $key->getValue() : $key;
|
||
}
|
||
|
||
/**
|
||
* field分析
|
||
* @access protected
|
||
* @param Query $query 查询对象
|
||
* @param mixed $fields 字段名
|
||
* @return string
|
||
*/
|
||
protected function parseField(Query $query, $fields)
|
||
{
|
||
if ('*' == $fields || empty($fields)) {
|
||
$fieldsStr = '*';
|
||
} elseif (is_array($fields)) {
|
||
// 支持 'field1'=>'field2' 这样的字段别名定义
|
||
$array = [];
|
||
|
||
foreach ($fields as $key => $field) {
|
||
if (!is_numeric($key)) {
|
||
$array[] = $this->parseKey($query, $key) . ' AS ' . $this->parseKey($query, $field, true);
|
||
} else {
|
||
$array[] = $this->parseKey($query, $field);
|
||
}
|
||
}
|
||
|
||
$fieldsStr = implode(',', $array);
|
||
}
|
||
|
||
return $fieldsStr;
|
||
}
|
||
|
||
/**
|
||
* table分析
|
||
* @access protected
|
||
* @param Query $query 查询对象
|
||
* @param mixed $tables 表名
|
||
* @return string
|
||
*/
|
||
protected function parseTable(Query $query, $tables)
|
||
{
|
||
$item = [];
|
||
$options = $query->getOptions();
|
||
|
||
foreach ((array) $tables as $key => $table) {
|
||
if (!is_numeric($key)) {
|
||
$key = $this->connection->parseSqlTable($key);
|
||
$item[] = $this->parseKey($query, $key) . ' ' . $this->parseKey($query, $table);
|
||
} else {
|
||
$table = $this->connection->parseSqlTable($table);
|
||
|
||
if (isset($options['alias'][$table])) {
|
||
$item[] = $this->parseKey($query, $table) . ' ' . $this->parseKey($query, $options['alias'][$table]);
|
||
} else {
|
||
$item[] = $this->parseKey($query, $table);
|
||
}
|
||
}
|
||
}
|
||
|
||
return implode(',', $item);
|
||
}
|
||
|
||
/**
|
||
* where分析
|
||
* @access protected
|
||
* @param Query $query 查询对象
|
||
* @param mixed $where 查询条件
|
||
* @return string
|
||
*/
|
||
protected function parseWhere(Query $query, $where)
|
||
{
|
||
$options = $query->getOptions();
|
||
$whereStr = $this->buildWhere($query, $where);
|
||
|
||
if (!empty($options['soft_delete'])) {
|
||
// 附加软删除条件
|
||
list($field, $condition) = $options['soft_delete'];
|
||
|
||
$binds = $this->connection->getFieldsBind($options['table']);
|
||
$whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : '';
|
||
$whereStr = $whereStr . $this->parseWhereItem($query, $field, $condition, '', $binds);
|
||
}
|
||
|
||
return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
|
||
}
|
||
|
||
/**
|
||
* 生成查询条件SQL
|
||
* @access public
|
||
* @param Query $query 查询对象
|
||
* @param mixed $where 查询条件
|
||
* @return string
|
||
*/
|
||
public function buildWhere(Query $query, $where)
|
||
{
|
||
if (empty($where)) {
|
||
$where = [];
|
||
}
|
||
|
||
$whereStr = '';
|
||
$binds = $this->connection->getFieldsBind($query->getOptions('table'));
|
||
|
||
foreach ($where as $logic => $val) {
|
||
$str = [];
|
||
|
||
foreach ($val as $value) {
|
||
if ($value instanceof Expression) {
|
||
$str[] = ' ' . $logic . ' ( ' . $value->getValue() . ' )';
|
||
continue;
|
||
}
|
||
|
||
if (is_array($value)) {
|
||
if (key($value) !== 0) {
|
||
throw new Exception('where express error:' . var_export($value, true));
|
||
}
|
||
$field = array_shift($value);
|
||
} elseif (!($value instanceof \Closure)) {
|
||
throw new Exception('where express error:' . var_export($value, true));
|
||
}
|
||
|
||
if ($value instanceof \Closure) {
|
||
// 使用闭包查询
|
||
$newQuery = $query->newQuery()->setConnection($this->connection);
|
||
$value($newQuery);
|
||
$whereClause = $this->buildWhere($query, $newQuery->getOptions('where'));
|
||
|
||
if (!empty($whereClause)) {
|
||
$str[] = ' ' . $logic . ' ( ' . $whereClause . ' )';
|
||
}
|
||
} elseif (is_array($field)) {
|
||
array_unshift($value, $field);
|
||
$str2 = [];
|
||
foreach ($value as $item) {
|
||
$str2[] = $this->parseWhereItem($query, array_shift($item), $item, $logic, $binds);
|
||
}
|
||
|
||
$str[] = ' ' . $logic . ' ( ' . implode(' AND ', $str2) . ' )';
|
||
} elseif (strpos($field, '|')) {
|
||
// 不同字段使用相同查询条件(OR)
|
||
$array = explode('|', $field);
|
||
$item = [];
|
||
|
||
foreach ($array as $k) {
|
||
$item[] = $this->parseWhereItem($query, $k, $value, '', $binds);
|
||
}
|
||
|
||
$str[] = ' ' . $logic . ' ( ' . implode(' OR ', $item) . ' )';
|
||
} elseif (strpos($field, '&')) {
|
||
// 不同字段使用相同查询条件(AND)
|
||
$array = explode('&', $field);
|
||
$item = [];
|
||
|
||
foreach ($array as $k) {
|
||
$item[] = $this->parseWhereItem($query, $k, $value, '', $binds);
|
||
}
|
||
|
||
$str[] = ' ' . $logic . ' ( ' . implode(' AND ', $item) . ' )';
|
||
} else {
|
||
// 对字段使用表达式查询
|
||
$field = is_string($field) ? $field : '';
|
||
$str[] = ' ' . $logic . ' ' . $this->parseWhereItem($query, $field, $value, $logic, $binds);
|
||
}
|
||
}
|
||
|
||
$whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($logic) + 1) : implode(' ', $str);
|
||
}
|
||
|
||
return $whereStr;
|
||
}
|
||
|
||
// where子单元分析
|
||
protected function parseWhereItem(Query $query, $field, $val, $rule = '', $binds = [])
|
||
{
|
||
// 字段分析
|
||
$key = $field ? $this->parseKey($query, $field, true) : '';
|
||
|
||
// 查询规则和条件
|
||
if (!is_array($val)) {
|
||
$val = is_null($val) ? ['NULL', ''] : ['=', $val];
|
||
}
|
||
|
||
list($exp, $value) = $val;
|
||
|
||
// 对一个字段使用多个查询条件
|
||
if (is_array($exp)) {
|
||
$item = array_pop($val);
|
||
|
||
// 传入 or 或者 and
|
||
if (is_string($item) && in_array($item, ['AND', 'and', 'OR', 'or'])) {
|
||
$rule = $item;
|
||
} else {
|
||
array_push($val, $item);
|
||
}
|
||
|
||
foreach ($val as $k => $item) {
|
||
$str[] = $this->parseWhereItem($query, $field, $item, $rule, $binds);
|
||
}
|
||
|
||
return '( ' . implode(' ' . $rule . ' ', $str) . ' )';
|
||
}
|
||
|
||
// 检测操作符
|
||
$exp = strtoupper($exp);
|
||
if (isset($this->exp[$exp])) {
|
||