Builder.php 36 KB

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