Builder.php 39 KB

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