<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think\db;
use Closure;
use PDO;
use think\db\exception\DbException as Exception;
abstract class Builder
{
protected $connection;
protected $exp = ['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'],
];
protected $selectSql = 'SELECT%DISTINCT%%EXTRA% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%';
protected $insertSql = '%INSERT%%EXTRA% INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%';
protected $insertAllSql = '%INSERT%%EXTRA% INTO %TABLE% (%FIELD%) %DATA% %COMMENT%';
protected $updateSql = 'UPDATE%EXTRA% %TABLE% SET %SET%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%';
protected $deleteSql = 'DELETE%EXTRA% FROM %TABLE%%USING%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%';
public function __construct(ConnectionInterface $connection)
{
$this->connection = $connection;
}
public function getConnection(): ConnectionInterface
{
return $this->connection;
}
public function bindParser(string $name, array $parser)
{
$this->parser[$name] = $parser;
return $this;
}
protected function parseData(Query $query, array $data = [], array $fields = [], array $bind = []): array
{
if (empty($data)) {
return [];
}
$options = $query->getOptions();
if (empty($bind)) {
$bind = $query->getFieldsBindType();
}
if (empty($fields)) {
if (empty($options['field']) || '*' == $options['field']) {
$fields = array_keys($bind);
} else {
$fields = $options['field'];
}
}
$result = [];
foreach ($data as $key => $val) {
$item = $this->parseKey($query, $key, true);
if ($val instanceof Raw) {
$result[$item] = $this->parseRaw($query, $val);
continue;
} elseif (!is_scalar($val) && (in_array($key, (array) $query->getOptions('json')) || 'json' == $query->getFieldType($key))) {
$val = json_encode($val);
}
if (false !== strpos($key, '->')) {
[$key, $name] = explode('->', $key, 2);
$item = $this->parseKey($query, $key);
$result[$item] = 'json_set(' . $item . ', \'$.' . $name . '\', ' . $this->parseDataBind($query, $key . '->' . $name, $val, $bind) . ')';
} elseif (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) && is_string($val[0])) {
switch (strtoupper($val[0])) {
case 'INC':
$result[$item] = $item . ' + ' . floatval($val[1]);
break;
case 'DEC':
$result[$item] = $item . ' - ' . floatval($val[1]);
break;
}
} elseif (is_scalar($val)) {
$result[$item] = $this->parseDataBind($query, $key, $val, $bind);
}
}
return $result;
}
protected function parseDataBind(Query $query, string $key, $data, array $bind = []): string
{
if ($data instanceof Raw) {
return $this->parseRaw($query, $data);
}
$name = $query->bindValue($data, $bind[$key] ?? PDO::PARAM_STR);
return ':' . $name;
}
public function parseKey(Query $query, $key, bool $strict = false): string
{
return $key;
}
protected function parseExtra(Query $query, string $extra): string
{
return preg_match('/^[\w]+$/i', $extra) ? ' ' . strtoupper($extra) : '';
}
protected function parseField(Query $query, $fields): string
{
if (is_array($fields)) {
$array = [];
foreach ($fields as $key => $field) {
if ($field instanceof Raw) {
$array[] = $this->parseRaw($query, $field);
} elseif (!is_numeric($key)) {
$array[] = $this->parseKey($query, $key) . ' AS ' . $this->parseKey($query, $field, true);
} else {
$array[] = $this->parseKey($query, $field);
}
}
$fieldsStr = implode(',', $array);
} else {
$fieldsStr = '*';
}
return $fieldsStr;
}
protected function parseTable(Query $query, $tables): string
{
$item = [];
$options = $query->getOptions();
foreach ((array) $tables as $key => $table) {
if ($table instanceof Raw) {
$item[] = $this->parseRaw($query, $table);
} elseif (!is_numeric($key)) {
$item[] = $this->parseKey($query, $key) . ' ' . $this->parseKey($query, $table);
} elseif (isset($options['alias'][$table])) {
$item[] = $this->parseKey($query, $table) . ' ' . $this->parseKey($query, $options['alias'][$table]);
} else {
$item[] = $this->parseKey($query, $table);
}
}
return implode(',', $item);
}
protected function parseWhere(Query $query, array $where): string
{
$options = $query->getOptions();
$whereStr = $this->buildWhere($query, $where);
if (!empty($options['soft_delete'])) {
[$field, $condition] = $options['soft_delete'];
$binds = $query->getFieldsBindType();
$whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : '';
$whereStr = $whereStr . $this->parseWhereItem($query, $field, $condition, $binds);
}
return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
}
public function buildWhere(Query $query, array $where): string
{
if (empty($where)) {
$where = [];
}
$whereStr = '';
$binds = $query->getFieldsBindType();
foreach ($where as $logic => $val) {
$str = $this->parseWhereLogic($query, $logic, $val, $binds);
$whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($logic) + 1) : implode(' ', $str);
}
return $whereStr;
}
protected function parseWhereLogic(Query $query, string $logic, array $val, array $binds = []): array
{
$where = [];
foreach ($val as $value) {
if ($value instanceof Raw) {
$where[] = ' ' . $logic . ' ( ' . $this->parseRaw($query, $value) . ' )';
continue;
}
if (is_array($value)) {
if (key($value) !== 0) {
throw new Exception('where express error:' . var_export($value, true));
}
$field = array_shift($value);
} elseif (true === $value) {
$where[] = ' ' . $logic . ' 1 ';
continue;
} elseif (!($value instanceof Closure)) {
throw new Exception('where express error:' . var_export($value, true));
}
if ($value instanceof Closure) {
$whereClosureStr = $this->parseClosureWhere($query, $value, $logic);
if ($whereClosureStr) {
$where[] = $whereClosureStr;
}
} elseif (is_array($field)) {
$where[] = $this->parseMultiWhereField($query, $value, $field, $logic, $binds);
} elseif ($field instanceof Raw) {
$where[] = ' ' . $logic . ' ' . $this->parseWhereItem($query, $field, $value, $binds);
} elseif (strpos($field, '|')) {
$where[] = $this->parseFieldsOr($query, $value, $field, $logic, $binds);
} elseif (strpos($field, '&')) {
$where[] = $this->parseFieldsAnd($query, $value, $field, $logic, $binds);
} else {
$field = is_string($field) ? $field : '';
$where[] = ' ' . $logic . ' ' . $this->parseWhereItem($query, $field, $value, $binds);
}
}
return $where;
}
protected function parseFieldsAnd(Query $query, $value, string $field, string $logic, array $binds): string
{
$item = [];
foreach (explode('&', $field) as $k) {
$item[] = $this->parseWhereItem($query, $k, $value, $binds);
}
return ' ' . $logic . ' ( ' . implode(' AND ', $item) . ' )';
}
protected function parseFieldsOr(Query $query, $value, string $field, string $logic, array $binds): string
{
$item = [];
foreach (explode('|', $field) as $k) {
$item[] = $this->parseWhereItem($query, $k, $value, $binds);
}
return ' ' . $logic . ' ( ' . implode(' OR ', $item) . ' )';
}
protected function parseClosureWhere(Query $query, Closure $value, string $logic): string
{
$newQuery = $query->newQuery();
$value($newQuery);
$whereClosure = $this->buildWhere($newQuery, $newQuery->getOptions('where') ?: []);
if (!empty($whereClosure)) {
$query->bind($newQuery->getBind(false));
$where = ' ' . $logic . ' ( ' . $whereClosure . ' )';
}
return $where ?? '';
}
protected function parseMultiWhereField(Query $query, $value, $field, string $logic, array $binds): string
{
array_unshift($value, $field);
$where = [];
foreach ($value as $item) {
$where[] = $this->parseWhereItem($query, array_shift($item), $item, $binds);
}
return ' ' . $logic . ' ( ' . implode(' AND ', $where) . ' )';
}
protected function parseWhereItem(Query $query, $field, array $val, array $binds = []): string
{
$key = $field ? $this->parseKey($query, $field, true) : '';
[$exp, $value] = $val;
if (!is_string($exp)) {
throw new Exception('where express error:' . var_export($exp, true));
}
$exp = strtoupper($exp);
if (isset($this->exp[$exp])) {
$exp = $this->exp[$exp];
}
if (is_string($field) && 'LIKE' != $exp) {
$bindType = $binds[$field] ?? PDO::PARAM_STR;
} else {
$bindType = PDO::PARAM_STR;
}
if ($value instanceof Raw) {
} elseif (is_object($value) && method_exists($value, '__toString')) {
$value = $value->__toString();
}
if (is_scalar($value) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && strpos($exp, 'TIME') === false) {
if (is_string($value) && 0 === strpos($value, ':') && $query->isBind(substr($value, 1))) {
} else {
$name = $query->bindValue($value, $bindType);
$value = ':' . $name;
}
}
foreach ($this->parser as $fun => $parse) {
if (in_array($exp, $parse)) {
return $this->$fun($query, $key, $exp, $value, $field, $bindType, $val[2] ?? 'AND');
}
}
throw new Exception('where express error:' . $exp);
}
protected function parseLike(Query $query, string $key, string $exp, $value, $field, int $bindType, string $logic): string
{
if (is_array($value)) {
$array = [];
foreach ($value as $item) {
$name = $query->bindValue($item, PDO::PARAM_STR);
$array[] = $key . ' ' . $exp . ' :' . $name;
}
$whereStr = '(' . implode(' ' . strtoupper($logic) . ' ', $array) . ')';
} else {
$whereStr = $key . ' ' . $exp . ' ' . $value;
}
return $whereStr;
}
protected function parseExp(Query $query, string $key, string $exp, Raw $value, string $field, int $bindType): string
{
return '( ' . $key . ' ' . $this->parseRaw($query, $value) . ' )';
}
protected function parseColumn(Query $query, string $key, $exp, array $value, string $field, int $bindType): string
{
[$op, $field] = $value;
if (!in_array(trim($op), ['=', '<>', '>', '>=', '<', '<='])) {
throw new Exception('where express error:' . var_export($value, true));
}
return '( ' . $key . ' ' . $op . ' ' . $this->parseKey($query, $field, true) . ' )';
}
protected function parseNull(Query $query, string $key, string $exp, $value, $field, int $bindType): string
{
return $key . ' IS ' . $exp;
}
protected function parseBetween(Query $query, string $key, string $exp, $value, $field, int $bindType): string
{
$data = is_array($value) ? $value : explode(',', $value);
$min = $query->bindValue($data[0], $bindType);
$max = $query->bindValue($data[1], $bindType);
return $key . ' ' . $exp . ' :' . $min . ' AND :' . $max . ' ';
}
protected function parseExists(Query $query, string $key, string $exp, $value, string $field, int $bindType): string
{
if ($value instanceof Closure) {
$value = $this->parseClosure($query, $value, false);
} elseif ($value instanceof Raw) {
$value = $this->parseRaw($query, $value);
} else {
throw new Exception('where express error:' . $value);
}
return $exp . ' ( ' . $value . ' )';
}
protected function parseTime(Query $query, string $key, string $exp, $value, $field, int $bindType): string
{
return $key . ' ' . substr($exp, 0, 2) . ' ' . $this->parseDateTime($query, $value, $field, $bindType);
}
protected function parseCompare(Query $query, string $key, string $exp, $value, $field, int $bindType): string
{
if (is_array($value)) {
throw new Exception('where express error:' . $exp . var_export($value, true));
}
if ($value instanceof Closure) {
$value = $this->parseClosure($query, $value);
}
if ('=' == $exp && is_null($value)) {
return $key . ' IS NULL';
}
return $key . ' ' . $exp . ' ' . $value;
}
protected function parseBetweenTime(Query $query, string $key, string $exp, $value, $field, int $bindType): string
{
if (is_string($value)) {
$value = explode(',', $value);
}
return $key . ' ' . substr($exp, 0, -4)
. $this->parseDateTime($query, $value[0], $field, $bindType)
. ' AND '
. $this->parseDateTime($query, $value[1], $field, $bindType);
}
protected function parseIn(Query $query, string $key, string $exp, $value, $field, int $bindType): string
{
if ($value instanceof Closure) {
$value = $this->parseClosure($query, $value, false);
} elseif ($value instanceof Raw) {
$value = $this->parseRaw($query, $value);
} else {
$value = array_unique(is_array($value) ? $value : explode(',', $value));
if (count($value) === 0) {
return 'IN' == $exp ? '0 = 1' : '1 = 1';
}
$array = [];
foreach ($value as $v) {
$name = $query->bindValue($v, $bindType);
$array[] = ':' . $name;
}
if (count($array) == 1) {
return $key . ('IN' == $exp ? ' = ' : ' <> ') . $array[0];
} else {
$value = implode(',', $array);
}
}
return $key . ' ' . $exp . ' (' . $value . ')';
}
protected function parseClosure(Query $query, Closure $call, bool $show = true): string
{
$newQuery = $query->newQuery()->removeOption();
$call($newQuery);
return $newQuery->buildSql($show);
}
protected function parseDateTime(Query $query, $value, string $key, int $bindType): string
{
$options = $query->getOptions();
if (strpos($key, '.')) {
[$table, $key] = explode('.', $key);
if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) {
$table = $pos;
}
} else {
$table = $options['table'];
}
$type = $query->getFieldType($key);
if ($type) {
if (is_string($value)) {
$value = strtotime($value) ?: $value;
}
if (is_int($value)) {
if (preg_match('/(datetime|timestamp)/is', $type)) {
$value = date('Y-m-d H:i:s', $value);
} elseif (preg_match('/(date)/is', $type)) {
$value = date('Y-m-d', $value);
}
}
}
$name = $query->bindValue($value, $bindType);
return ':' . $name;
}
protected function parseLimit(Query $query, string $limit): string
{
return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
}
protected function parseJoin(Query $query, array $join): string
{
$joinStr = '';
foreach ($join as $item) {
[$table, $type, $on] = $item;
if (strpos($on, '=')) {
[$val1, $val2] = explode('=', $on, 2);
$condition = $this->parseKey($query, $val1) . '=' . $this->parseKey($query, $val2);
} else {
$condition = $on;
}
$table = $this->parseTable($query, $table);
$joinStr .= ' ' . $type . ' JOIN ' . $table . ' ON ' . $condition;
}
return $joinStr;
}
protected function parseOrder(Query $query, array $order): string
{
$array = [];
foreach ($order as $key => $val) {
if ($val instanceof Raw) {
$array[] = $this->parseRaw($query, $val);
} elseif (is_array($val) && preg_match('/^[\w\.]+$/', $key)) {
$array[] = $this->parseOrderField($query, $key, $val);
} elseif ('[rand]' == $val) {
$array[] = $this->parseRand($query);
} elseif (is_string($val)) {
if (is_numeric($key)) {
[$key, $sort] = explode(' ', strpos($val, ' ') ? $val : $val . ' ');
} else {
$sort = $val;
}
if (preg_match('/^[\w\.]+$/', $key)) {
$sort = strtoupper($sort);
$sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
$array[] = $this->parseKey($query, $key, true) . $sort;
} else {
throw new Exception('order express error:' . $key);
}
}
}
return empty($array) ? '' : ' ORDER BY ' . implode(',', $array);
}
protected function parseRaw(Query $query, Raw $raw): string
{
$sql = $raw->getValue();
$bind = $raw->getBind();
if ($bind) {
$query->bindParams($sql, $bind);
}
return $sql;
}
protected function parseRand(Query $query): string
{
return '';
}
protected function parseOrderField(Query $query, string $key, array $val): string
{
if (isset($val['sort'])) {
$sort = $val['sort'];
unset($val['sort']);
} else {
$sort = '';
}
$sort = strtoupper($sort);
$sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
$bind = $query->getFieldsBindType();
foreach ($val as $item) {
$val[] = $this->parseDataBind($query, $key, $item, $bind);
}
return 'field(' . $this->parseKey($query, $key, true) . ',' . implode(',', $val) . ')' . $sort;
}
protected function parseGroup(Query $query, $group): string
{
if (empty($group)) {
return '';
}
if (is_string($group)) {
$group = explode(',', $group);
}
$val = [];
foreach ($group as $key) {
$val[] = $this->parseKey($query, $key);
}
return ' GROUP BY ' . implode(',', $val);
}
protected function parseHaving(Query $query, string $having): string
{
return !empty($having) ? ' HAVING ' . $having : '';
}
protected function parseComment(Query $query, string $comment): string
{
if (false !== strpos($comment, '*/')) {
$comment = strstr($comment, '*/', true);
}
return !empty($comment) ? ' ' : '';
}
protected function parseDistinct(Query $query, bool $distinct): string
{
return !empty($distinct) ? ' DISTINCT ' : '';
}
protected function parseUnion(Query $query, array $union): string
{
if (empty($union)) {
return '';
}
$type = $union['type'];
unset($union['type']);
foreach ($union as $u) {
if ($u instanceof Closure) {
$sql[] = $type . ' ' . $this->parseClosure($query, $u);
} elseif (is_string($u)) {
$sql[] = $type . ' ( ' . $u . ' )';
}
}
return ' ' . implode(' ', $sql);
}
protected function parseForce(Query $query, $index): string
{
if (empty($index)) {
return '';
}
if (is_array($index)) {
$index = join(',', $index);
}
return sprintf(" FORCE INDEX ( %s ) ", $index);
}
protected function parseLock(Query $query, $lock = false): string
{
if (is_bool($lock)) {
return $lock ? ' FOR UPDATE ' : '';
}
if (is_string($lock) && !empty($lock)) {
return ' ' . trim($lock) . ' ';
} else {
return '';
}
}
public function select(Query $query, bool $one = false): string
{
$options = $query->getOptions();
return str_replace(
['%TABLE%', '%DISTINCT%', '%EXTRA%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
[
$this->parseTable($query, $options['table']),
$this->parseDistinct($query, $options['distinct']),
$this->parseExtra($query, $options['extra']),
$this->parseField($query, $options['field'] ?? '*'),
$this->parseJoin($query, $options['join']),
$this->parseWhere($query, $options['where']),
$this->parseGroup($query, $options['group']),
$this->parseHaving($query, $options['having']),
$this->parseOrder($query, $options['order']),
$this->parseLimit($query, $one ? '1' : $options['limit']),
$this->parseUnion($query, $options['union']),
$this->parseLock($query, $options['lock']),
$this->parseComment($query, $options['comment']),
$this->parseForce($query, $options['force']),
],
$this->selectSql);
}
public function insert(Query $query): string
{
$options = $query->getOptions();
$data = $this->parseData($query, $options['data']);
if (empty($data)) {
return '';
}
$fields = array_keys($data);
$values = array_values($data);
return str_replace(
['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'],
[
!empty($options['replace']) ? 'REPLACE' : 'INSERT',
$this->parseTable($query, $options['table']),
$this->parseExtra($query, $options['extra']),
implode(' , ', $fields),
implode(' , ', $values),
$this->parseComment($query, $options['comment']),
],
$this->insertSql);
}
public function insertAll(Query $query, array $dataSet): string
{
$options = $query->getOptions();
$bind = $query->getFieldsBindType();
if (empty($options['field']) || '*' == $options['field']) {
$allowFields = array_keys($bind);
} else {
$allowFields = $options['field'];
}
$fields = [];
$values = [];
foreach ($dataSet as $k => $data) {
$data = $this->parseData($query, $data, $allowFields, $bind);
$values[] = 'SELECT ' . implode(',', array_values($data));
if (!isset($insertFields)) {
$insertFields = array_keys($data);
}
}
foreach ($insertFields as $field) {
$fields[] = $this->parseKey($query, $field);
}
return str_replace(
['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'],
[
!empty($options['replace']) ? 'REPLACE' : 'INSERT',
$this->parseTable($query, $options['table']),
$this->parseExtra($query, $options['extra']),
implode(' , ', $fields),
implode(' UNION ALL ', $values),
$this->parseComment($query, $options['comment']),
],
$this->insertAllSql);
}
public function selectInsert(Query $query, array $fields, string $table): string
{
foreach ($fields as &$field) {
$field = $this->parseKey($query, $field, true);
}
return 'INSERT INTO ' . $this->parseTable($query, $table) . ' (' . implode(',', $fields) . ') ' . $this->select($query);
}
public function update(Query $query): string
{
$options = $query->getOptions();
$data = $this->parseData($query, $options['data']);
if (empty($data)) {
return '';
}
$set = [];
foreach ($data as $key => $val) {
$set[] = $key . ' = ' . $val;
}
return str_replace(
['%TABLE%', '%EXTRA%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
[
$this->parseTable($query, $options['table']),
$this->parseExtra($query, $options['extra']),
implode(' , ', $set),
$this->parseJoin($query, $options['join']),
$this->parseWhere($query, $options['where']),
$this->parseOrder($query, $options['order']),
$this->parseLimit($query, $options['limit']),
$this->parseLock($query, $options['lock']),
$this->parseComment($query, $options['comment']),
],
$this->updateSql);
}
public function delete(Query $query): string
{
$options = $query->getOptions();
return str_replace(
['%TABLE%', '%EXTRA%', '%USING%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
[
$this->parseTable($query, $options['table']),
$this->parseExtra($query, $options['extra']),
!empty($options['using']) ? ' USING ' . $this->parseTable($query, $options['using']) . ' ' : '',
$this->parseJoin($query, $options['join']),
$this->parseWhere($query, $options['where']),
$this->parseOrder($query, $options['order']),
$this->parseLimit($query, $options['limit']),
$this->parseLock($query, $options['lock']),
$this->parseComment($query, $options['comment']),
],
$this->deleteSql);
}
}