Builder.php 40 KB

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