Builder.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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. * 生成insertall SQL
  1084. * @access public
  1085. * @param Query $query 查询对象
  1086. * @param array $keys 字段名
  1087. * @param array $datas 数据
  1088. * @return string
  1089. */
  1090. public function insertAllByKeys(Query $query, array $keys, array $datas): string
  1091. {
  1092. $options = $query->getOptions();
  1093. // 获取绑定信息
  1094. $bind = $query->getFieldsBindType();
  1095. $fields = [];
  1096. $values = [];
  1097. foreach ($keys as $field) {
  1098. $fields[] = $this->parseKey($query, $field);
  1099. }
  1100. foreach ($datas as $data) {
  1101. foreach ($data as $key => &$val) {
  1102. if (!$query->isAutoBind()) {
  1103. $val = PDO::PARAM_STR == $bind[$keys[$key]] ? '\'' . $val . '\'' : $val;
  1104. } else {
  1105. $val = $this->parseDataBind($query, $keys[$key], $val, $bind);
  1106. }
  1107. }
  1108. $values[] = 'SELECT ' . implode(',', $data);
  1109. }
  1110. return str_replace(
  1111. ['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'],
  1112. [
  1113. !empty($options['replace']) ? 'REPLACE' : 'INSERT',
  1114. $this->parseTable($query, $options['table']),
  1115. $this->parseExtra($query, $options['extra']),
  1116. implode(' , ', $fields),
  1117. implode(' UNION ALL ', $values),
  1118. $this->parseComment($query, $options['comment']),
  1119. ],
  1120. $this->insertAllSql
  1121. );
  1122. }
  1123. /**
  1124. * 生成slect insert SQL
  1125. * @access public
  1126. * @param Query $query 查询对象
  1127. * @param array $fields 数据
  1128. * @param string $table 数据表
  1129. * @return string
  1130. */
  1131. public function selectInsert(Query $query, array $fields, string $table): string
  1132. {
  1133. foreach ($fields as &$field) {
  1134. $field = $this->parseKey($query, $field, true);
  1135. }
  1136. return 'INSERT INTO ' . $this->parseTable($query, $table) . ' (' . implode(',', $fields) . ') ' . $this->select($query);
  1137. }
  1138. /**
  1139. * 生成update SQL
  1140. * @access public
  1141. * @param Query $query 查询对象
  1142. * @return string
  1143. */
  1144. public function update(Query $query): string
  1145. {
  1146. $options = $query->getOptions();
  1147. $data = $this->parseData($query, $options['data']);
  1148. if (empty($data)) {
  1149. return '';
  1150. }
  1151. $set = [];
  1152. foreach ($data as $key => $val) {
  1153. $set[] = $key . ' = ' . $val;
  1154. }
  1155. return str_replace(
  1156. ['%TABLE%', '%EXTRA%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  1157. [
  1158. $this->parseTable($query, $options['table']),
  1159. $this->parseExtra($query, $options['extra']),
  1160. implode(' , ', $set),
  1161. $this->parseJoin($query, $options['join']),
  1162. $this->parseWhere($query, $options['where']),
  1163. $this->parseOrder($query, $options['order']),
  1164. $this->parseLimit($query, $options['limit']),
  1165. $this->parseLock($query, $options['lock']),
  1166. $this->parseComment($query, $options['comment']),
  1167. ],
  1168. $this->updateSql
  1169. );
  1170. }
  1171. /**
  1172. * 生成delete SQL
  1173. * @access public
  1174. * @param Query $query 查询对象
  1175. * @return string
  1176. */
  1177. public function delete(Query $query): string
  1178. {
  1179. $options = $query->getOptions();
  1180. return str_replace(
  1181. ['%TABLE%', '%EXTRA%', '%USING%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  1182. [
  1183. $this->parseTable($query, $options['table']),
  1184. $this->parseExtra($query, $options['extra']),
  1185. !empty($options['using']) ? ' USING ' . $this->parseTable($query, $options['using']) . ' ' : '',
  1186. $this->parseJoin($query, $options['join']),
  1187. $this->parseWhere($query, $options['where']),
  1188. $this->parseOrder($query, $options['order']),
  1189. $this->parseLimit($query, $options['limit']),
  1190. $this->parseLock($query, $options['lock']),
  1191. $this->parseComment($query, $options['comment']),
  1192. ],
  1193. $this->deleteSql
  1194. );
  1195. }
  1196. }