Builder.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\db;
  12. use PDO;
  13. use think\Exception;
  14. abstract class Builder
  15. {
  16. // connection对象实例
  17. protected $connection;
  18. // 查询表达式映射
  19. 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'];
  20. // 查询表达式解析
  21. protected $parser = [
  22. 'parseCompare' => ['=', '<>', '>', '>=', '<', '<='],
  23. 'parseLike' => ['LIKE', 'NOT LIKE'],
  24. 'parseBetween' => ['NOT BETWEEN', 'BETWEEN'],
  25. 'parseIn' => ['NOT IN', 'IN'],
  26. 'parseExp' => ['EXP'],
  27. 'parseNull' => ['NOT NULL', 'NULL'],
  28. 'parseBetweenTime' => ['BETWEEN TIME', 'NOT BETWEEN TIME'],
  29. 'parseTime' => ['< TIME', '> TIME', '<= TIME', '>= TIME'],
  30. 'parseExists' => ['NOT EXISTS', 'EXISTS'],
  31. 'parseColumn' => ['COLUMN'],
  32. ];
  33. // SQL表达式
  34. protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%';
  35. protected $insertSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%';
  36. protected $insertAllSql = '%INSERT% INTO %TABLE% (%FIELD%) %DATA% %COMMENT%';
  37. protected $updateSql = 'UPDATE %TABLE% SET %SET%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%';
  38. protected $deleteSql = 'DELETE FROM %TABLE%%USING%%JOIN%%WHERE%%ORDER%%LIMIT% %LOCK%%COMMENT%';
  39. /**
  40. * 架构函数
  41. * @access public
  42. * @param Connection $connection 数据库连接对象实例
  43. */
  44. public function __construct(Connection $connection)
  45. {
  46. $this->connection = $connection;
  47. }
  48. /**
  49. * 获取当前的连接对象实例
  50. * @access public
  51. * @return Connection
  52. */
  53. public function getConnection()
  54. {
  55. return $this->connection;
  56. }
  57. /**
  58. * 注册查询表达式解析
  59. * @access public
  60. * @param string $name 解析方法
  61. * @param array $parser 匹配表达式数据
  62. * @return $this
  63. */
  64. public function bindParser($name, $parser)
  65. {
  66. $this->parser[$name] = $parser;
  67. return $this;
  68. }
  69. /**
  70. * 数据分析
  71. * @access protected
  72. * @param Query $query 查询对象
  73. * @param array $data 数据
  74. * @param array $fields 字段信息
  75. * @param array $bind 参数绑定
  76. * @return array
  77. */
  78. protected function parseData(Query $query, $data = [], $fields = [], $bind = [])
  79. {
  80. if (empty($data)) {
  81. return [];
  82. }
  83. $options = $query->getOptions();
  84. // 获取绑定信息
  85. if (empty($bind)) {
  86. $bind = $this->connection->getFieldsBind($options['table']);
  87. }
  88. if (empty($fields)) {
  89. if ('*' == $options['field']) {
  90. $fields = array_keys($bind);
  91. } else {
  92. $fields = $options['field'];
  93. }
  94. }
  95. $result = [];
  96. foreach ($data as $key => $val) {
  97. if ('*' != $options['field'] && !in_array($key, $fields, true)) {
  98. continue;
  99. }
  100. $item = $this->parseKey($query, $key, true);
  101. if ($val instanceof Expression) {
  102. $result[$item] = $val->getValue();
  103. continue;
  104. } elseif (!is_scalar($val) && (in_array($key, (array) $query->getOptions('json')) || 'json' == $this->connection->getFieldsType($options['table'], $key))) {
  105. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  106. } elseif (is_object($val) && method_exists($val, '__toString')) {
  107. // 对象数据写入
  108. $val = $val->__toString();
  109. }
  110. if (false !== strpos($key, '->')) {
  111. list($key, $name) = explode('->', $key);
  112. $item = $this->parseKey($query, $key);
  113. $result[$item] = 'json_set(' . $item . ', \'$.' . $name . '\', ' . $this->parseDataBind($query, $key, $val, $bind) . ')';
  114. } elseif ('*' == $options['field'] && false === strpos($key, '.') && !in_array($key, $fields, true)) {
  115. if ($options['strict']) {
  116. throw new Exception('fields not exists:[' . $key . ']');
  117. }
  118. } elseif (is_null($val)) {
  119. $result[$item] = 'NULL';
  120. } elseif (is_array($val) && !empty($val)) {
  121. switch (strtoupper($val[0])) {
  122. case 'INC':
  123. $result[$item] = $item . ' + ' . floatval($val[1]);
  124. break;
  125. case 'DEC':
  126. $result[$item] = $item . ' - ' . floatval($val[1]);
  127. break;
  128. case 'EXP':
  129. throw new Exception('not support data:[' . $val[0] . ']');
  130. }
  131. } elseif (is_scalar($val)) {
  132. // 过滤非标量数据
  133. $result[$item] = $this->parseDataBind($query, $key, $val, $bind);
  134. }
  135. }
  136. return $result;
  137. }
  138. /**
  139. * 数据绑定处理
  140. * @access protected
  141. * @param Query $query 查询对象
  142. * @param string $key 字段名
  143. * @param mixed $data 数据
  144. * @param array $bind 绑定数据
  145. * @return string
  146. */
  147. protected function parseDataBind(Query $query, $key, $data, $bind = [])
  148. {
  149. if ($data instanceof Expression) {
  150. return $data->getValue();
  151. }
  152. $name = $query->bind($data, isset($bind[$key]) ? $bind[$key] : PDO::PARAM_STR);
  153. return ':' . $name;
  154. }
  155. /**
  156. * 字段名分析
  157. * @access public
  158. * @param Query $query 查询对象
  159. * @param mixed $key 字段名
  160. * @param bool $strict 严格检测
  161. * @return string
  162. */
  163. public function parseKey(Query $query, $key, $strict = false)
  164. {
  165. return $key instanceof Expression ? $key->getValue() : $key;
  166. }
  167. /**
  168. * field分析
  169. * @access protected
  170. * @param Query $query 查询对象
  171. * @param mixed $fields 字段名
  172. * @return string
  173. */
  174. protected function parseField(Query $query, $fields)
  175. {
  176. if ('*' == $fields || empty($fields)) {
  177. $fieldsStr = '*';
  178. } elseif (is_array($fields)) {
  179. // 支持 'field1'=>'field2' 这样的字段别名定义
  180. $array = [];
  181. foreach ($fields as $key => $field) {
  182. if (!is_numeric($key)) {
  183. $array[] = $this->parseKey($query, $key) . ' AS ' . $this->parseKey($query, $field, true);
  184. } else {
  185. $array[] = $this->parseKey($query, $field);
  186. }
  187. }
  188. $fieldsStr = implode(',', $array);
  189. }
  190. return $fieldsStr;
  191. }
  192. /**
  193. * table分析
  194. * @access protected
  195. * @param Query $query 查询对象
  196. * @param mixed $tables 表名
  197. * @return string
  198. */
  199. protected function parseTable(Query $query, $tables)
  200. {
  201. $item = [];
  202. $options = $query->getOptions();
  203. foreach ((array) $tables as $key => $table) {
  204. if (!is_numeric($key)) {
  205. $key = $this->connection->parseSqlTable($key);
  206. $item[] = $this->parseKey($query, $key) . ' ' . $this->parseKey($query, $table);
  207. } else {
  208. $table = $this->connection->parseSqlTable($table);
  209. if (isset($options['alias'][$table])) {
  210. $item[] = $this->parseKey($query, $table) . ' ' . $this->parseKey($query, $options['alias'][$table]);
  211. } else {
  212. $item[] = $this->parseKey($query, $table);
  213. }
  214. }
  215. }
  216. return implode(',', $item);
  217. }
  218. /**
  219. * where分析
  220. * @access protected
  221. * @param Query $query 查询对象
  222. * @param mixed $where 查询条件
  223. * @return string
  224. */
  225. protected function parseWhere(Query $query, $where)
  226. {
  227. $options = $query->getOptions();
  228. $whereStr = $this->buildWhere($query, $where);
  229. if (!empty($options['soft_delete'])) {
  230. // 附加软删除条件
  231. list($field, $condition) = $options['soft_delete'];
  232. $binds = $this->connection->getFieldsBind($options['table']);
  233. $whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : '';
  234. $whereStr = $whereStr . $this->parseWhereItem($query, $field, $condition, '', $binds);
  235. }
  236. return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
  237. }
  238. /**
  239. * 生成查询条件SQL
  240. * @access public
  241. * @param Query $query 查询对象
  242. * @param mixed $where 查询条件
  243. * @return string
  244. */
  245. public function buildWhere(Query $query, $where)
  246. {
  247. if (empty($where)) {
  248. $where = [];
  249. }
  250. $whereStr = '';
  251. $binds = $this->connection->getFieldsBind($query->getOptions('table'));
  252. foreach ($where as $logic => $val) {
  253. $str = [];
  254. foreach ($val as $value) {
  255. if ($value instanceof Expression) {
  256. $str[] = ' ' . $logic . ' ( ' . $value->getValue() . ' )';
  257. continue;
  258. }
  259. if (is_array($value)) {
  260. if (key($value) !== 0) {
  261. throw new Exception('where express error:' . var_export($value, true));
  262. }
  263. $field = array_shift($value);
  264. } elseif (!($value instanceof \Closure)) {
  265. throw new Exception('where express error:' . var_export($value, true));
  266. }
  267. if ($value instanceof \Closure) {
  268. // 使用闭包查询
  269. $newQuery = $query->newQuery()->setConnection($this->connection);
  270. $value($newQuery);
  271. $whereClause = $this->buildWhere($query, $newQuery->getOptions('where'));
  272. if (!empty($whereClause)) {
  273. $str[] = ' ' . $logic . ' ( ' . $whereClause . ' )';
  274. }
  275. } elseif (is_array($field)) {
  276. array_unshift($value, $field);
  277. $str2 = [];
  278. foreach ($value as $item) {
  279. $str2[] = $this->parseWhereItem($query, array_shift($item), $item, $logic, $binds);
  280. }
  281. $str[] = ' ' . $logic . ' ( ' . implode(' AND ', $str2) . ' )';
  282. } elseif (strpos($field, '|')) {
  283. // 不同字段使用相同查询条件(OR)
  284. $array = explode('|', $field);
  285. $item = [];
  286. foreach ($array as $k) {
  287. $item[] = $this->parseWhereItem($query, $k, $value, '', $binds);
  288. }
  289. $str[] = ' ' . $logic . ' ( ' . implode(' OR ', $item) . ' )';
  290. } elseif (strpos($field, '&')) {
  291. // 不同字段使用相同查询条件(AND)
  292. $array = explode('&', $field);
  293. $item = [];
  294. foreach ($array as $k) {
  295. $item[] = $this->parseWhereItem($query, $k, $value, '', $binds);
  296. }
  297. $str[] = ' ' . $logic . ' ( ' . implode(' AND ', $item) . ' )';
  298. } else {
  299. // 对字段使用表达式查询
  300. $field = is_string($field) ? $field : '';
  301. $str[] = ' ' . $logic . ' ' . $this->parseWhereItem($query, $field, $value, $logic, $binds);
  302. }
  303. }
  304. $whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($logic) + 1) : implode(' ', $str);
  305. }
  306. return $whereStr;
  307. }
  308. // where子单元分析
  309. protected function parseWhereItem(Query $query, $field, $val, $rule = '', $binds = [])
  310. {
  311. // 字段分析
  312. $key = $field ? $this->parseKey($query, $field, true) : '';
  313. // 查询规则和条件
  314. if (!is_array($val)) {
  315. $val = is_null($val) ? ['NULL', ''] : ['=', $val];
  316. }
  317. list($exp, $value) = $val;
  318. // 对一个字段使用多个查询条件
  319. if (is_array($exp)) {
  320. $item = array_pop($val);
  321. // 传入 or 或者 and
  322. if (is_string($item) && in_array($item, ['AND', 'and', 'OR', 'or'])) {
  323. $rule = $item;
  324. } else {
  325. array_push($val, $item);
  326. }
  327. foreach ($val as $k => $item) {
  328. $str[] = $this->parseWhereItem($query, $field, $item, $rule, $binds);
  329. }
  330. return '( ' . implode(' ' . $rule . ' ', $str) . ' )';
  331. }
  332. // 检测操作符
  333. $exp = strtoupper($exp);
  334. if (isset($this->exp[$exp])) {
  335. $exp = $this->exp[$exp];
  336. }
  337. if ($value instanceof Expression) {
  338. } elseif (is_object($value) && method_exists($value, '__toString')) {
  339. // 对象数据写入
  340. $value = $value->__toString();
  341. }
  342. if (strpos($field, '->')) {
  343. $jsonType = $query->getJsonFieldType($field);
  344. $bindType = $this->connection->getFieldBindType($jsonType);
  345. } else {
  346. $bindType = isset($binds[$field]) ? $binds[$field] : PDO::PARAM_STR;
  347. }
  348. if (is_scalar($value) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && strpos($exp, 'TIME') === false) {
  349. if (0 === strpos($value, ':') && $query->isBind(substr($value, 1))) {
  350. } else {
  351. $name = $query->bind($value, $bindType);
  352. $value = ':' . $name;
  353. }
  354. }
  355. // 解析查询表达式
  356. foreach ($this->parser as $fun => $parse) {
  357. if (in_array($exp, $parse)) {
  358. $whereStr = $this->$fun($query, $key, $exp, $value, $field, $bindType, isset($val[2]) ? $val[2] : 'AND');
  359. break;
  360. }
  361. }
  362. if (!isset($whereStr)) {
  363. throw new Exception('where express error:' . $exp);
  364. }
  365. return $whereStr;
  366. }
  367. /**
  368. * 模糊查询
  369. * @access protected
  370. * @param Query $query 查询对象
  371. * @param string $key
  372. * @param string $exp
  373. * @param mixed $value
  374. * @param string $field
  375. * @param integer $bindType
  376. * @param string $logic
  377. * @return string
  378. */
  379. protected function parseLike(Query $query, $key, $exp, $value, $field, $bindType, $logic)
  380. {
  381. // 模糊匹配
  382. if (is_array($value)) {
  383. foreach ($value as $item) {
  384. $name = $query->bind($item, $bindType);
  385. $array[] = $key . ' ' . $exp . ' :' . $name;
  386. }
  387. $whereStr = '(' . implode(' ' . strtoupper($logic) . ' ', $array) . ')';
  388. } else {
  389. $whereStr = $key . ' ' . $exp . ' ' . $value;
  390. }
  391. return $whereStr;
  392. }
  393. /**
  394. * 表达式查询
  395. * @access protected
  396. * @param Query $query 查询对象
  397. * @param string $key
  398. * @param string $exp
  399. * @param array $value
  400. * @param string $field
  401. * @param integer $bindType
  402. * @return string
  403. */
  404. protected function parseColumn(Query $query, $key, $exp, array $value, $field, $bindType)
  405. {
  406. // 字段比较查询
  407. list($op, $field2) = $value;
  408. if (!in_array($op, ['=', '<>', '>', '>=', '<', '<='])) {
  409. throw new Exception('where express error:' . var_export($value, true));
  410. }
  411. return '( ' . $key . ' ' . $op . ' ' . $this->parseKey($query, $field2, true) . ' )';
  412. }
  413. /**
  414. * 表达式查询
  415. * @access protected
  416. * @param Query $query 查询对象
  417. * @param string $key
  418. * @param string $exp
  419. * @param Expression $value
  420. * @param string $field
  421. * @param integer $bindType
  422. * @return string
  423. */
  424. protected function parseExp(Query $query, $key, $exp, Expression $value, $field, $bindType)
  425. {
  426. // 表达式查询
  427. return '( ' . $key . ' ' . $value->getValue() . ' )';
  428. }
  429. /**
  430. * Null查询
  431. * @access protected
  432. * @param Query $query 查询对象
  433. * @param string $key
  434. * @param string $exp
  435. * @param mixed $value
  436. * @param string $field
  437. * @param integer $bindType
  438. * @return string
  439. */
  440. protected function parseNull(Query $query, $key, $exp, $value, $field, $bindType)
  441. {
  442. // NULL 查询
  443. return $key . ' IS ' . $exp;
  444. }
  445. /**
  446. * 范围查询
  447. * @access protected
  448. * @param Query $query 查询对象
  449. * @param string $key
  450. * @param string $exp
  451. * @param mixed $value
  452. * @param string $field
  453. * @param integer $bindType
  454. * @return string
  455. */
  456. protected function parseBetween(Query $query, $key, $exp, $value, $field, $bindType)
  457. {
  458. // BETWEEN 查询
  459. $data = is_array($value) ? $value : explode(',', $value);
  460. $min = $query->bind($data[0], $bindType);
  461. $max = $query->bind($data[1], $bindType);
  462. return $key . ' ' . $exp . ' :' . $min . ' AND :' . $max . ' ';
  463. }
  464. /**
  465. * Exists查询
  466. * @access protected
  467. * @param Query $query 查询对象
  468. * @param string $key
  469. * @param string $exp
  470. * @param mixed $value
  471. * @param string $field
  472. * @param integer $bindType
  473. * @return string
  474. */
  475. protected function parseExists(Query $query, $key, $exp, $value, $field, $bindType)
  476. {
  477. // EXISTS 查询
  478. if ($value instanceof \Closure) {
  479. $value = $this->parseClosure($query, $value, false);
  480. } elseif ($value instanceof Expression) {
  481. $value = $value->getValue();
  482. } else {
  483. throw new Exception('where express error:' . $value);
  484. }
  485. return $exp . ' (' . $value . ')';
  486. }
  487. /**
  488. * 时间比较查询
  489. * @access protected
  490. * @param Query $query 查询对象
  491. * @param string $key
  492. * @param string $exp
  493. * @param mixed $value
  494. * @param string $field
  495. * @param integer $bindType
  496. * @return string
  497. */
  498. protected function parseTime(Query $query, $key, $exp, $value, $field, $bindType)
  499. {
  500. return $key . ' ' . substr($exp, 0, 2) . ' ' . $this->parseDateTime($query, $value, $field, $bindType);
  501. }
  502. /**
  503. * 大小比较查询
  504. * @access protected
  505. * @param Query $query 查询对象
  506. * @param string $key
  507. * @param string $exp
  508. * @param mixed $value
  509. * @param string $field
  510. * @param integer $bindType
  511. * @return string
  512. */
  513. protected function parseCompare(Query $query, $key, $exp, $value, $field, $bindType)
  514. {
  515. if (is_array($value)) {
  516. throw new Exception('where express error:' . $exp . var_export($value, true));
  517. }
  518. // 比较运算
  519. if ($value instanceof \Closure) {
  520. $value = $this->parseClosure($query, $value);
  521. }
  522. return $key . ' ' . $exp . ' ' . $value;
  523. }
  524. /**
  525. * 时间范围查询
  526. * @access protected
  527. * @param Query $query 查询对象
  528. * @param string $key
  529. * @param string $exp
  530. * @param mixed $value
  531. * @param string $field
  532. * @param integer $bindType
  533. * @return string
  534. */
  535. protected function parseBetweenTime(Query $query, $key, $exp, $value, $field, $bindType)
  536. {
  537. if (is_string($value)) {
  538. $value = explode(',', $value);
  539. }
  540. return $key . ' ' . substr($exp, 0, -4)
  541. . $this->parseDateTime($query, $value[0], $field, $bindType)
  542. . ' AND '
  543. . $this->parseDateTime($query, $value[1], $field, $bindType);
  544. }
  545. /**
  546. * IN查询
  547. * @access protected
  548. * @param Query $query 查询对象
  549. * @param string $key
  550. * @param string $exp
  551. * @param mixed $value
  552. * @param string $field
  553. * @param integer $bindType
  554. * @return string
  555. */
  556. protected function parseIn(Query $query, $key, $exp, $value, $field, $bindType)
  557. {
  558. // IN 查询
  559. if ($value instanceof \Closure) {
  560. $value = $this->parseClosure($query, $value, false);
  561. } elseif ($value instanceof Expression) {
  562. $value = $value->getValue();
  563. } else {
  564. $value = array_unique(is_array($value) ? $value : explode(',', $value));
  565. $array = [];
  566. foreach ($value as $k => $v) {
  567. $name = $query->bind($v, $bindType);
  568. $array[] = ':' . $name;
  569. }
  570. $zone = implode(',', $array);
  571. $value = empty($zone) ? "''" : $zone;
  572. }
  573. return $key . ' ' . $exp . ' (' . $value . ')';
  574. }
  575. /**
  576. * 闭包子查询
  577. * @access protected
  578. * @param Query $query 查询对象
  579. * @param \Closure $call
  580. * @param bool $show
  581. * @return string
  582. */
  583. protected function parseClosure(Query $query, $call, $show = true)
  584. {
  585. $newQuery = $query->newQuery()->setConnection($this->connection);
  586. $call($newQuery);
  587. return $newQuery->buildSql($show);
  588. }
  589. /**
  590. * 日期时间条件解析
  591. * @access protected
  592. * @param Query $query 查询对象
  593. * @param string $value
  594. * @param string $key
  595. * @param integer $bindType
  596. * @return string
  597. */
  598. protected function parseDateTime(Query $query, $value, $key, $bindType = null)
  599. {
  600. $options = $query->getOptions();
  601. // 获取时间字段类型
  602. if (strpos($key, '.')) {
  603. list($table, $key) = explode('.', $key);
  604. if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) {
  605. $table = $pos;
  606. }
  607. } else {
  608. $table = $options['table'];
  609. }
  610. $type = $this->connection->getTableInfo($table, 'type');
  611. if (isset($type[$key])) {
  612. $info = $type[$key];
  613. }
  614. if (isset($info)) {
  615. if (is_string($value)) {
  616. $value = strtotime($value) ?: $value;
  617. }
  618. if (preg_match('/(datetime|timestamp)/is', $info)) {
  619. // 日期及时间戳类型
  620. $value = date('Y-m-d H:i:s', $value);
  621. } elseif (preg_match('/(date)/is', $info)) {
  622. // 日期及时间戳类型
  623. $value = date('Y-m-d', $value);
  624. }
  625. }
  626. $name = $query->bind($value, $bindType);
  627. return ':' . $name;
  628. }
  629. /**
  630. * limit分析
  631. * @access protected
  632. * @param Query $query 查询对象
  633. * @param mixed $limit
  634. * @return string
  635. */
  636. protected function parseLimit(Query $query, $limit)
  637. {
  638. return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
  639. }
  640. /**
  641. * join分析
  642. * @access protected
  643. * @param Query $query 查询对象
  644. * @param array $join
  645. * @return string
  646. */
  647. protected function parseJoin(Query $query, $join)
  648. {
  649. $joinStr = '';
  650. if (!empty($join)) {
  651. foreach ($join as $item) {
  652. list($table, $type, $on) = $item;
  653. $condition = [];
  654. foreach ((array) $on as $val) {
  655. if ($val instanceof Expression) {
  656. $condition[] = $val->getValue();
  657. } elseif (strpos($val, '=')) {
  658. list($val1, $val2) = explode('=', $val, 2);
  659. $condition[] = $this->parseKey($query, $val1) . '=' . $this->parseKey($query, $val2);
  660. } else {
  661. $condition[] = $val;
  662. }
  663. }
  664. $table = $this->parseTable($query, $table);
  665. $joinStr .= ' ' . $type . ' JOIN ' . $table . ' ON ' . implode(' AND ', $condition);
  666. }
  667. }
  668. return $joinStr;
  669. }
  670. /**
  671. * order分析
  672. * @access protected
  673. * @param Query $query 查询对象
  674. * @param mixed $order
  675. * @return string
  676. */
  677. protected function parseOrder(Query $query, $order)
  678. {
  679. foreach ($order as $key => $val) {
  680. if ($val instanceof Expression) {
  681. $array[] = $val->getValue();
  682. } elseif (is_array($val) && preg_match('/^[\w\.]+$/', $key)) {
  683. $array[] = $this->parseOrderField($query, $key, $val);
  684. } elseif ('[rand]' == $val) {
  685. $array[] = $this->parseRand($query);
  686. } elseif (is_string($val)) {
  687. if (is_numeric($key)) {
  688. list($key, $sort) = explode(' ', strpos($val, ' ') ? $val : $val . ' ');
  689. } else {
  690. $sort = $val;
  691. }
  692. if (preg_match('/^[\w\.]+$/', $key)) {
  693. $sort = strtoupper($sort);
  694. $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
  695. $array[] = $this->parseKey($query, $key, true) . $sort;
  696. } else {
  697. throw new Exception('order express error:' . $key);
  698. }
  699. }
  700. }
  701. return empty($array) ? '' : ' ORDER BY ' . implode(',', $array);
  702. }
  703. /**
  704. * orderField分析
  705. * @access protected
  706. * @param Query $query 查询对象
  707. * @param mixed $key
  708. * @param array $val
  709. * @return string
  710. */
  711. protected function parseOrderField($query, $key, $val)
  712. {
  713. if (isset($val['sort'])) {
  714. $sort = $val['sort'];
  715. unset($val['sort']);
  716. } else {
  717. $sort = '';
  718. }
  719. $sort = strtoupper($sort);
  720. $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
  721. $options = $query->getOptions();
  722. $bind = $this->connection->getFieldsBind($options['table']);
  723. foreach ($val as $k => $item) {
  724. $val[$k] = $this->parseDataBind($query, $key, $item, $bind);
  725. }
  726. return 'field(' . $this->parseKey($query, $key, true) . ',' . implode(',', $val) . ')' . $sort;
  727. }
  728. /**
  729. * group分析
  730. * @access protected
  731. * @param Query $query 查询对象
  732. * @param mixed $group
  733. * @return string
  734. */
  735. protected function parseGroup(Query $query, $group)
  736. {
  737. if (empty($group)) {
  738. return '';
  739. }
  740. if (is_string($group)) {
  741. $group = explode(',', $group);
  742. }
  743. foreach ($group as $key) {
  744. $val[] = $this->parseKey($query, $key);
  745. }
  746. return ' GROUP BY ' . implode(',', $val);
  747. }
  748. /**
  749. * having分析
  750. * @access protected
  751. * @param Query $query 查询对象
  752. * @param string $having
  753. * @return string
  754. */
  755. protected function parseHaving(Query $query, $having)
  756. {
  757. return !empty($having) ? ' HAVING ' . $having : '';
  758. }
  759. /**
  760. * comment分析
  761. * @access protected
  762. * @param Query $query 查询对象
  763. * @param string $comment
  764. * @return string
  765. */
  766. protected function parseComment(Query $query, $comment)
  767. {
  768. if (false !== strpos($comment, '*/')) {
  769. $comment = strstr($comment, '*/', true);
  770. }
  771. return !empty($comment) ? ' /* ' . $comment . ' */' : '';
  772. }
  773. /**
  774. * distinct分析
  775. * @access protected
  776. * @param Query $query 查询对象
  777. * @param mixed $distinct
  778. * @return string
  779. */
  780. protected function parseDistinct(Query $query, $distinct)
  781. {
  782. return !empty($distinct) ? ' DISTINCT ' : '';
  783. }
  784. /**
  785. * union分析
  786. * @access protected
  787. * @param Query $query 查询对象
  788. * @param mixed $union
  789. * @return string
  790. */
  791. protected function parseUnion(Query $query, $union)
  792. {
  793. if (empty($union)) {
  794. return '';
  795. }
  796. $type = $union['type'];
  797. unset($union['type']);
  798. foreach ($union as $u) {
  799. if ($u instanceof \Closure) {
  800. $sql[] = $type . ' ' . $this->parseClosure($query, $u);
  801. } elseif (is_string($u)) {
  802. $sql[] = $type . ' ( ' . $this->connection->parseSqlTable($u) . ' )';
  803. }
  804. }
  805. return ' ' . implode(' ', $sql);
  806. }
  807. /**
  808. * index分析,可在操作链中指定需要强制使用的索引
  809. * @access protected
  810. * @param Query $query 查询对象
  811. * @param mixed $index
  812. * @return string
  813. */
  814. protected function parseForce(Query $query, $index)
  815. {
  816. if (empty($index)) {
  817. return '';
  818. }
  819. return sprintf(" FORCE INDEX ( %s ) ", is_array($index) ? implode(',', $index) : $index);
  820. }
  821. /**
  822. * 设置锁机制
  823. * @access protected
  824. * @param Query $query 查询对象
  825. * @param bool|string $lock
  826. * @return string
  827. */
  828. protected function parseLock(Query $query, $lock = false)
  829. {
  830. if (is_bool($lock)) {
  831. return $lock ? ' FOR UPDATE ' : '';
  832. } elseif (is_string($lock) && !empty($lock)) {
  833. return ' ' . trim($lock) . ' ';
  834. }
  835. }
  836. /**
  837. * 生成查询SQL
  838. * @access public
  839. * @param Query $query 查询对象
  840. * @return string
  841. */
  842. public function select(Query $query)
  843. {
  844. $options = $query->getOptions();
  845. return str_replace(
  846. ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
  847. [
  848. $this->parseTable($query, $options['table']),
  849. $this->parseDistinct($query, $options['distinct']),
  850. $this->parseField($query, $options['field']),
  851. $this->parseJoin($query, $options['join']),
  852. $this->parseWhere($query, $options['where']),
  853. $this->parseGroup($query, $options['group']),
  854. $this->parseHaving($query, $options['having']),
  855. $this->parseOrder($query, $options['order']),
  856. $this->parseLimit($query, $options['limit']),
  857. $this->parseUnion($query, $options['union']),
  858. $this->parseLock($query, $options['lock']),
  859. $this->parseComment($query, $options['comment']),
  860. $this->parseForce($query, $options['force']),
  861. ],
  862. $this->selectSql);
  863. }
  864. /**
  865. * 生成Insert SQL
  866. * @access public
  867. * @param Query $query 查询对象
  868. * @param bool $replace 是否replace
  869. * @return string
  870. */
  871. public function insert(Query $query, $replace = false)
  872. {
  873. $options = $query->getOptions();
  874. // 分析并处理数据
  875. $data = $this->parseData($query, $options['data']);
  876. if (empty($data)) {
  877. return '';
  878. }
  879. $fields = array_keys($data);
  880. $values = array_values($data);
  881. return str_replace(
  882. ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
  883. [
  884. $replace ? 'REPLACE' : 'INSERT',
  885. $this->parseTable($query, $options['table']),
  886. implode(' , ', $fields),
  887. implode(' , ', $values),
  888. $this->parseComment($query, $options['comment']),
  889. ],
  890. $this->insertSql);
  891. }
  892. /**
  893. * 生成insertall SQL
  894. * @access public
  895. * @param Query $query 查询对象
  896. * @param array $dataSet 数据集
  897. * @param bool $replace 是否replace
  898. * @return string
  899. */
  900. public function insertAll(Query $query, $dataSet, $replace = false)
  901. {
  902. $options = $query->getOptions();
  903. // 获取合法的字段
  904. if ('*' == $options['field']) {
  905. $allowFields = $this->connection->getTableFields($options['table']);
  906. } else {
  907. $allowFields = $options['field'];
  908. }
  909. // 获取绑定信息
  910. $bind = $this->connection->getFieldsBind($options['table']);
  911. foreach ($dataSet as $data) {
  912. $data = $this->parseData($query, $data, $allowFields, $bind);
  913. $values[] = 'SELECT ' . implode(',', array_values($data));
  914. if (!isset($insertFields)) {
  915. $insertFields = array_keys($data);
  916. }
  917. }
  918. $fields = [];
  919. foreach ($insertFields as $field) {
  920. $fields[] = $this->parseKey($query, $field);
  921. }
  922. return str_replace(
  923. ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
  924. [
  925. $replace ? 'REPLACE' : 'INSERT',
  926. $this->parseTable($query, $options['table']),
  927. implode(' , ', $fields),
  928. implode(' UNION ALL ', $values),
  929. $this->parseComment($query, $options['comment']),
  930. ],
  931. $this->insertAllSql);
  932. }
  933. /**
  934. * 生成slect insert SQL
  935. * @access public
  936. * @param Query $query 查询对象
  937. * @param array $fields 数据
  938. * @param string $table 数据表
  939. * @return string
  940. */
  941. public function selectInsert(Query $query, $fields, $table)
  942. {
  943. if (is_string($fields)) {
  944. $fields = explode(',', $fields);
  945. }
  946. foreach ($fields as &$field) {
  947. $field = $this->parseKey($query, $field, true);
  948. }
  949. return 'INSERT INTO ' . $this->parseTable($query, $table) . ' (' . implode(',', $fields) . ') ' . $this->select($query);
  950. }
  951. /**
  952. * 生成update SQL
  953. * @access public
  954. * @param Query $query 查询对象
  955. * @return string
  956. */
  957. public function update(Query $query)
  958. {
  959. $options = $query->getOptions();
  960. $data = $this->parseData($query, $options['data']);
  961. if (empty($data)) {
  962. return '';
  963. }
  964. foreach ($data as $key => $val) {
  965. $set[] = $key . ' = ' . $val;
  966. }
  967. return str_replace(
  968. ['%TABLE%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  969. [
  970. $this->parseTable($query, $options['table']),
  971. implode(' , ', $set),
  972. $this->parseJoin($query, $options['join']),
  973. $this->parseWhere($query, $options['where']),
  974. $this->parseOrder($query, $options['order']),
  975. $this->parseLimit($query, $options['limit']),
  976. $this->parseLock($query, $options['lock']),
  977. $this->parseComment($query, $options['comment']),
  978. ],
  979. $this->updateSql);
  980. }
  981. /**
  982. * 生成delete SQL
  983. * @access public
  984. * @param Query $query 查询对象
  985. * @return string
  986. */
  987. public function delete(Query $query)
  988. {
  989. $options = $query->getOptions();
  990. return str_replace(
  991. ['%TABLE%', '%USING%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  992. [
  993. $this->parseTable($query, $options['table']),
  994. !empty($options['using']) ? ' USING ' . $this->parseTable($query, $options['using']) . ' ' : '',
  995. $this->parseJoin($query, $options['join']),
  996. $this->parseWhere($query, $options['where']),
  997. $this->parseOrder($query, $options['order']),
  998. $this->parseLimit($query, $options['limit']),
  999. $this->parseLock($query, $options['lock']),
  1000. $this->parseComment($query, $options['comment']),
  1001. ],
  1002. $this->deleteSql);
  1003. }
  1004. }