Builder.php 39 KB

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