You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

900 lines
32 KiB

  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\db;
  12. use PDO;
  13. use think\Exception;
  14. abstract class Builder
  15. {
  16. // connection对象实例
  17. protected $connection;
  18. // 查询对象实例
  19. protected $query;
  20. // 数据库表达式
  21. protected $exp = ['eq' => '=', 'neq' => '<>', 'gt' => '>', 'egt' => '>=', 'lt' => '<', 'elt' => '<=', 'notlike' => 'NOT LIKE', 'not like' => 'NOT LIKE', 'like' => 'LIKE', 'in' => 'IN', 'exp' => 'EXP', 'notin' => 'NOT IN', 'not in' => 'NOT IN', 'between' => 'BETWEEN', 'not between' => 'NOT BETWEEN', 'notbetween' => 'NOT BETWEEN', 'exists' => 'EXISTS', 'notexists' => 'NOT EXISTS', 'not exists' => 'NOT EXISTS', 'null' => 'NULL', 'notnull' => 'NOT NULL', 'not null' => 'NOT NULL', '> time' => '> TIME', '< time' => '< TIME', '>= time' => '>= TIME', '<= time' => '<= TIME', 'between time' => 'BETWEEN TIME', 'not between time' => 'NOT BETWEEN TIME', 'notbetween time' => 'NOT BETWEEN TIME'];
  22. // SQL表达式
  23. protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT%%LOCK%%COMMENT%';
  24. protected $insertSql = '%INSERT% INTO %TABLE% (%FIELD%) VALUES (%DATA%) %COMMENT%';
  25. protected $insertAllSql = '%INSERT% INTO %TABLE% (%FIELD%) %DATA% %COMMENT%';
  26. protected $updateSql = 'UPDATE %TABLE% SET %SET% %JOIN% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%';
  27. protected $deleteSql = 'DELETE FROM %TABLE% %USING% %JOIN% %WHERE% %ORDER%%LIMIT% %LOCK%%COMMENT%';
  28. /**
  29. * 构造函数
  30. * @access public
  31. * @param Connection $connection 数据库连接对象实例
  32. * @param Query $query 数据库查询对象实例
  33. */
  34. public function __construct(Connection $connection, Query $query)
  35. {
  36. $this->connection = $connection;
  37. $this->query = $query;
  38. }
  39. /**
  40. * 获取当前的连接对象实例
  41. * @access public
  42. * @return Connection
  43. */
  44. public function getConnection()
  45. {
  46. return $this->connection;
  47. }
  48. /**
  49. * 获取当前的Query对象实例
  50. * @access public
  51. * @return Query
  52. */
  53. public function getQuery()
  54. {
  55. return $this->query;
  56. }
  57. /**
  58. * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写)
  59. * @access protected
  60. * @param string $sql sql语句
  61. * @return string
  62. */
  63. protected function parseSqlTable($sql)
  64. {
  65. return $this->query->parseSqlTable($sql);
  66. }
  67. /**
  68. * 数据分析
  69. * @access protected
  70. * @param array $data 数据
  71. * @param array $options 查询参数
  72. * @return array
  73. * @throws Exception
  74. */
  75. protected function parseData($data, $options)
  76. {
  77. if (empty($data)) {
  78. return [];
  79. }
  80. // 获取绑定信息
  81. $bind = $this->query->getFieldsBind($options['table']);
  82. if ('*' == $options['field']) {
  83. $fields = array_keys($bind);
  84. } else {
  85. $fields = $options['field'];
  86. }
  87. $result = [];
  88. foreach ($data as $key => $val) {
  89. if ('*' != $options['field'] && !in_array($key, $fields, true)) {
  90. continue;
  91. }
  92. $item = $this->parseKey($key, $options, true);
  93. if ($val instanceof Expression) {
  94. $result[$item] = $val->getValue();
  95. continue;
  96. } elseif (is_object($val) && method_exists($val, '__toString')) {
  97. // 对象数据写入
  98. $val = $val->__toString();
  99. }
  100. if (false === strpos($key, '.') && !in_array($key, $fields, true)) {
  101. if ($options['strict']) {
  102. throw new Exception('fields not exists:[' . $key . ']');
  103. }
  104. } elseif (is_null($val)) {
  105. $result[$item] = 'NULL';
  106. } elseif (is_array($val) && !empty($val)) {
  107. switch (strtolower($val[0])) {
  108. case 'inc':
  109. $result[$item] = $item . '+' . floatval($val[1]);
  110. break;
  111. case 'dec':
  112. $result[$item] = $item . '-' . floatval($val[1]);
  113. break;
  114. case 'exp':
  115. throw new Exception('not support data:[' . $val[0] . ']');
  116. }
  117. } elseif (is_scalar($val)) {
  118. // 过滤非标量数据
  119. if (0 === strpos($val, ':') && $this->query->isBind(substr($val, 1))) {
  120. $result[$item] = $val;
  121. } else {
  122. $key = str_replace('.', '_', $key);
  123. $this->query->bind('data__' . $key, $val, isset($bind[$key]) ? $bind[$key] : PDO::PARAM_STR);
  124. $result[$item] = ':data__' . $key;
  125. }
  126. }
  127. }
  128. return $result;
  129. }
  130. /**
  131. * 字段名分析
  132. * @access protected
  133. * @param string $key
  134. * @param array $options
  135. * @return string
  136. */
  137. protected function parseKey($key, $options = [], $strict = false)
  138. {
  139. return $key;
  140. }
  141. /**
  142. * value分析
  143. * @access protected
  144. * @param mixed $value
  145. * @param string $field
  146. * @return string|array
  147. */
  148. protected function parseValue($value, $field = '')
  149. {
  150. if (is_string($value)) {
  151. $value = strpos($value, ':') === 0 && $this->query->isBind(substr($value, 1)) ? $value : $this->connection->quote($value);
  152. } elseif (is_array($value)) {
  153. $value = array_map([$this, 'parseValue'], $value);
  154. } elseif (is_bool($value)) {
  155. $value = $value ? '1' : '0';
  156. } elseif (is_null($value)) {
  157. $value = 'null';
  158. }
  159. return $value;
  160. }
  161. /**
  162. * field分析
  163. * @access protected
  164. * @param mixed $fields
  165. * @param array $options
  166. * @return string
  167. */
  168. protected function parseField($fields, $options = [])
  169. {
  170. if ('*' == $fields || empty($fields)) {
  171. $fieldsStr = '*';
  172. } elseif (is_array($fields)) {
  173. // 支持 'field1'=>'field2' 这样的字段别名定义
  174. $array = [];
  175. foreach ($fields as $key => $field) {
  176. if ($field instanceof Expression) {
  177. $array[] = $field->getValue();
  178. } elseif (!is_numeric($key)) {
  179. $array[] = $this->parseKey($key, $options) . ' AS ' . $this->parseKey($field, $options, true);
  180. } else {
  181. $array[] = $this->parseKey($field, $options);
  182. }
  183. }
  184. $fieldsStr = implode(',', $array);
  185. }
  186. return $fieldsStr;
  187. }
  188. /**
  189. * table分析
  190. * @access protected
  191. * @param mixed $tables
  192. * @param array $options
  193. * @return string
  194. */
  195. protected function parseTable($tables, $options = [])
  196. {
  197. $item = [];
  198. foreach ((array) $tables as $key => $table) {
  199. if (!is_numeric($key)) {
  200. $key = $this->parseSqlTable($key);
  201. $item[] = $this->parseKey($key) . ' ' . (isset($options['alias'][$table]) ? $this->parseKey($options['alias'][$table]) : $this->parseKey($table));
  202. } else {
  203. $table = $this->parseSqlTable($table);
  204. if (isset($options['alias'][$table])) {
  205. $item[] = $this->parseKey($table) . ' ' . $this->parseKey($options['alias'][$table]);
  206. } else {
  207. $item[] = $this->parseKey($table);
  208. }
  209. }
  210. }
  211. return implode(',', $item);
  212. }
  213. /**
  214. * where分析
  215. * @access protected
  216. * @param mixed $where 查询条件
  217. * @param array $options 查询参数
  218. * @return string
  219. */
  220. protected function parseWhere($where, $options)
  221. {
  222. $whereStr = $this->buildWhere($where, $options);
  223. if (!empty($options['soft_delete'])) {
  224. // 附加软删除条件
  225. list($field, $condition) = $options['soft_delete'];
  226. $binds = $this->query->getFieldsBind($options['table']);
  227. $whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : '';
  228. $whereStr = $whereStr . $this->parseWhereItem($field, $condition, '', $options, $binds);
  229. }
  230. return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
  231. }
  232. /**
  233. * 生成查询条件SQL
  234. * @access public
  235. * @param mixed $where
  236. * @param array $options
  237. * @return string
  238. */
  239. public function buildWhere($where, $options)
  240. {
  241. if (empty($where)) {
  242. $where = [];
  243. }
  244. if ($where instanceof Query) {
  245. return $this->buildWhere($where->getOptions('where'), $options);
  246. }
  247. $whereStr = '';
  248. $binds = $this->query->getFieldsBind($options['table']);
  249. foreach ($where as $key => $val) {
  250. $str = [];
  251. foreach ($val as $field => $value) {
  252. if ($value instanceof Expression) {
  253. $str[] = ' ' . $key . ' ( ' . $value->getValue() . ' )';
  254. } elseif ($value instanceof \Closure) {
  255. // 使用闭包查询
  256. $query = new Query($this->connection);
  257. call_user_func_array($value, [ & $query]);
  258. $whereClause = $this->buildWhere($query->getOptions('where'), $options);
  259. if (!empty($whereClause)) {
  260. $str[] = ' ' . $key . ' ( ' . $whereClause . ' )';
  261. }
  262. } elseif (strpos($field, '|')) {
  263. // 不同字段使用相同查询条件(OR)
  264. $array = explode('|', $field);
  265. $item = [];
  266. foreach ($array as $k) {
  267. $item[] = $this->parseWhereItem($k, $value, '', $options, $binds);
  268. }
  269. $str[] = ' ' . $key . ' ( ' . implode(' OR ', $item) . ' )';
  270. } elseif (strpos($field, '&')) {
  271. // 不同字段使用相同查询条件(AND)
  272. $array = explode('&', $field);
  273. $item = [];
  274. foreach ($array as $k) {
  275. $item[] = $this->parseWhereItem($k, $value, '', $options, $binds);
  276. }
  277. $str[] = ' ' . $key . ' ( ' . implode(' AND ', $item) . ' )';
  278. } else {
  279. // 对字段使用表达式查询
  280. $field = is_string($field) ? $field : '';
  281. $str[] = ' ' . $key . ' ' . $this->parseWhereItem($field, $value, $key, $options, $binds);
  282. }
  283. }
  284. $whereStr .= empty($whereStr) ? substr(implode(' ', $str), strlen($key) + 1) : implode(' ', $str);
  285. }
  286. return $whereStr;
  287. }
  288. // where子单元分析
  289. protected function parseWhereItem($field, $val, $rule = '', $options = [], $binds = [], $bindName = null)
  290. {
  291. // 字段分析
  292. $key = $field ? $this->parseKey($field, $options, true) : '';
  293. // 查询规则和条件
  294. if (!is_array($val)) {
  295. $val = is_null($val) ? ['null', ''] : ['=', $val];
  296. }
  297. list($exp, $value) = $val;
  298. // 对一个字段使用多个查询条件
  299. if (is_array($exp)) {
  300. $item = array_pop($val);
  301. // 传入 or 或者 and
  302. if (is_string($item) && in_array($item, ['AND', 'and', 'OR', 'or'])) {
  303. $rule = $item;
  304. } else {
  305. array_push($val, $item);
  306. }
  307. foreach ($val as $k => $item) {
  308. $bindName = 'where_' . str_replace('.', '_', $field) . '_' . $k;
  309. $str[] = $this->parseWhereItem($field, $item, $rule, $options, $binds, $bindName);
  310. }
  311. return '( ' . implode(' ' . $rule . ' ', $str) . ' )';
  312. }
  313. // 检测操作符
  314. if (!in_array($exp, $this->exp)) {
  315. $exp = strtolower($exp);
  316. if (isset($this->exp[$exp])) {
  317. $exp = $this->exp[$exp];
  318. } else {
  319. throw new Exception('where express error:' . $exp);
  320. }
  321. }
  322. $bindName = $bindName ?: 'where_' . $rule . '_' . str_replace(['.', '-'], '_', $field);
  323. if (preg_match('/\W/', $bindName)) {
  324. // 处理带非单词字符的字段名
  325. $bindName = md5($bindName);
  326. }
  327. if ($value instanceof Expression) {
  328. } elseif (is_object($value) && method_exists($value, '__toString')) {
  329. // 对象数据写入
  330. $value = $value->__toString();
  331. }
  332. $bindType = isset($binds[$field]) ? $binds[$field] : PDO::PARAM_STR;
  333. if (is_scalar($value) && array_key_exists($field, $binds) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && strpos($exp, 'TIME') === false) {
  334. if (strpos($value, ':') !== 0 || !$this->query->isBind(substr($value, 1))) {
  335. if ($this->query->isBind($bindName)) {
  336. $bindName .= '_' . str_replace('.', '_', uniqid('', true));
  337. }
  338. $this->query->bind($bindName, $value, $bindType);
  339. $value = ':' . $bindName;
  340. }
  341. }
  342. $whereStr = '';
  343. if (in_array($exp, ['=', '<>', '>', '>=', '<', '<='])) {
  344. // 比较运算
  345. if ($value instanceof \Closure) {
  346. $whereStr .= $key . ' ' . $exp . ' ' . $this->parseClosure($value);
  347. } else {
  348. $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($value, $field);
  349. }
  350. } elseif ('LIKE' == $exp || 'NOT LIKE' == $exp) {
  351. // 模糊匹配
  352. if (is_array($value)) {
  353. foreach ($value as $item) {
  354. $array[] = $key . ' ' . $exp . ' ' . $this->parseValue($item, $field);
  355. }
  356. $logic = isset($val[2]) ? $val[2] : 'AND';
  357. $whereStr .= '(' . implode($array, ' ' . strtoupper($logic) . ' ') . ')';
  358. } else {
  359. $whereStr .= $key . ' ' . $exp . ' ' . $this->parseValue($value, $field);
  360. }
  361. } elseif ('EXP' == $exp) {
  362. // 表达式查询
  363. if ($value instanceof Expression) {
  364. $whereStr .= '( ' . $key . ' ' . $value->getValue() . ' )';
  365. } else {
  366. throw new Exception('where express error:' . $exp);
  367. }
  368. } elseif (in_array($exp, ['NOT NULL', 'NULL'])) {
  369. // NULL 查询
  370. $whereStr .= $key . ' IS ' . $exp;
  371. } elseif (in_array($exp, ['NOT IN', 'IN'])) {
  372. // IN 查询
  373. if ($value instanceof \Closure) {
  374. $whereStr .= $key . ' ' . $exp . ' ' . $this->parseClosure($value);
  375. } else {
  376. $value = array_unique(is_array($value) ? $value : explode(',', $value));
  377. if (array_key_exists($field, $binds)) {
  378. $bind = [];
  379. $array = [];
  380. $i = 0;
  381. foreach ($value as $v) {
  382. $i++;
  383. if ($this->query->isBind($bindName . '_in_' . $i)) {
  384. $bindKey = $bindName . '_in_' . uniqid() . '_' . $i;
  385. } else {
  386. $bindKey = $bindName . '_in_' . $i;
  387. }
  388. $bind[$bindKey] = [$v, $bindType];
  389. $array[] = ':' . $bindKey;
  390. }
  391. $this->query->bind($bind);
  392. $zone = implode(',', $array);
  393. } else {
  394. $zone = implode(',', $this->parseValue($value, $field));
  395. }
  396. $whereStr .= $key . ' ' . $exp . ' (' . (empty($zone) ? "''" : $zone) . ')';
  397. }
  398. } elseif (in_array($exp, ['NOT BETWEEN', 'BETWEEN'])) {
  399. // BETWEEN 查询
  400. $data = is_array($value) ? $value : explode(',', $value);
  401. if (array_key_exists($field, $binds)) {
  402. if ($this->query->isBind($bindName . '_between_1')) {
  403. $bindKey1 = $bindName . '_between_1' . uniqid();
  404. $bindKey2 = $bindName . '_between_2' . uniqid();
  405. } else {
  406. $bindKey1 = $bindName . '_between_1';
  407. $bindKey2 = $bindName . '_between_2';
  408. }
  409. $bind = [
  410. $bindKey1 => [$data[0], $bindType],
  411. $bindKey2 => [$data[1], $bindType],
  412. ];
  413. $this->query->bind($bind);
  414. $between = ':' . $bindKey1 . ' AND :' . $bindKey2;
  415. } else {
  416. $between = $this->parseValue($data[0], $field) . ' AND ' . $this->parseValue($data[1], $field);
  417. }
  418. $whereStr .= $key . ' ' . $exp . ' ' . $between;
  419. } elseif (in_array($exp, ['NOT EXISTS', 'EXISTS'])) {
  420. // EXISTS 查询
  421. if ($value instanceof \Closure) {
  422. $whereStr .= $exp . ' ' . $this->parseClosure($value);
  423. } else {
  424. $whereStr .= $exp . ' (' . $value . ')';
  425. }
  426. } elseif (in_array($exp, ['< TIME', '> TIME', '<= TIME', '>= TIME'])) {
  427. $whereStr .= $key . ' ' . substr($exp, 0, 2) . ' ' . $this->parseDateTime($value, $field, $options, $bindName, $bindType);
  428. } elseif (in_array($exp, ['BETWEEN TIME', 'NOT BETWEEN TIME'])) {
  429. if (is_string($value)) {
  430. $value = explode(',', $value);
  431. }
  432. $whereStr .= $key . ' ' . substr($exp, 0, -4) . $this->parseDateTime($value[0], $field, $options, $bindName . '_between_1', $bindType) . ' AND ' . $this->parseDateTime($value[1], $field, $options, $bindName . '_between_2', $bindType);
  433. }
  434. return $whereStr;
  435. }
  436. // 执行闭包子查询
  437. protected function parseClosure($call, $show = true)
  438. {
  439. $query = new Query($this->connection);
  440. call_user_func_array($call, [ & $query]);
  441. return $query->buildSql($show);
  442. }
  443. /**
  444. * 日期时间条件解析
  445. * @access protected
  446. * @param string $value
  447. * @param string $key
  448. * @param array $options
  449. * @param string $bindName
  450. * @param integer $bindType
  451. * @return string
  452. */
  453. protected function parseDateTime($value, $key, $options = [], $bindName = null, $bindType = null)
  454. {
  455. // 获取时间字段类型
  456. if (strpos($key, '.')) {
  457. list($table, $key) = explode('.', $key);
  458. if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) {
  459. $table = $pos;
  460. }
  461. } else {
  462. $table = $options['table'];
  463. }
  464. $type = $this->query->getTableInfo($table, 'type');
  465. if (isset($type[$key])) {
  466. $info = $type[$key];
  467. }
  468. if (isset($info)) {
  469. if (is_string($value)) {
  470. $value = strtotime($value) ?: $value;
  471. }
  472. if (preg_match('/(datetime|timestamp)/is', $info)) {
  473. // 日期及时间戳类型
  474. $value = date('Y-m-d H:i:s', $value);
  475. } elseif (preg_match('/(date)/is', $info)) {
  476. // 日期及时间戳类型
  477. $value = date('Y-m-d', $value);
  478. }
  479. }
  480. $bindName = $bindName ?: $key;
  481. if ($this->query->isBind($bindName)) {
  482. $bindName .= '_' . str_replace('.', '_', uniqid('', true));
  483. }
  484. $this->query->bind($bindName, $value, $bindType);
  485. return ':' . $bindName;
  486. }
  487. /**
  488. * limit分析
  489. * @access protected
  490. * @param mixed $limit
  491. * @return string
  492. */
  493. protected function parseLimit($limit)
  494. {
  495. return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
  496. }
  497. /**
  498. * join分析
  499. * @access protected
  500. * @param array $join
  501. * @param array $options 查询条件
  502. * @return string
  503. */
  504. protected function parseJoin($join, $options = [])
  505. {
  506. $joinStr = '';
  507. if (!empty($join)) {
  508. foreach ($join as $item) {
  509. list($table, $type, $on) = $item;
  510. $condition = [];
  511. foreach ((array) $on as $val) {
  512. if ($val instanceof Expression) {
  513. $condition[] = $val->getValue();
  514. } elseif (strpos($val, '=')) {
  515. list($val1, $val2) = explode('=', $val, 2);
  516. $condition[] = $this->parseKey($val1, $options) . '=' . $this->parseKey($val2, $options);
  517. } else {
  518. $condition[] = $val;
  519. }
  520. }
  521. $table = $this->parseTable($table, $options);
  522. $joinStr .= ' ' . $type . ' JOIN ' . $table . ' ON ' . implode(' AND ', $condition);
  523. }
  524. }
  525. return $joinStr;
  526. }
  527. /**
  528. * order分析
  529. * @access protected
  530. * @param mixed $order
  531. * @param array $options 查询条件
  532. * @return string
  533. */
  534. protected function parseOrder($order, $options = [])
  535. {
  536. if (empty($order)) {
  537. return '';
  538. }
  539. $array = [];
  540. foreach ($order as $key => $val) {
  541. if ($val instanceof Expression) {
  542. $array[] = $val->getValue();
  543. } elseif ('[rand]' == $val) {
  544. $array[] = $this->parseRand();
  545. } else {
  546. if (is_numeric($key)) {
  547. list($key, $sort) = explode(' ', strpos($val, ' ') ? $val : $val . ' ');
  548. } else {
  549. $sort = $val;
  550. }
  551. $sort = strtoupper($sort);
  552. $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
  553. $array[] = $this->parseKey($key, $options, true) . $sort;
  554. }
  555. }
  556. $order = implode(',', $array);
  557. return !empty($order) ? ' ORDER BY ' . $order : '';
  558. }
  559. /**
  560. * group分析
  561. * @access protected
  562. * @param mixed $group
  563. * @return string
  564. */
  565. protected function parseGroup($group)
  566. {
  567. return !empty($group) ? ' GROUP BY ' . $this->parseKey($group) : '';
  568. }
  569. /**
  570. * having分析
  571. * @access protected
  572. * @param string $having
  573. * @return string
  574. */
  575. protected function parseHaving($having)
  576. {
  577. return !empty($having) ? ' HAVING ' . $having : '';
  578. }
  579. /**
  580. * comment分析
  581. * @access protected
  582. * @param string $comment
  583. * @return string
  584. */
  585. protected function parseComment($comment)
  586. {
  587. if (false !== strpos($comment, '*/')) {
  588. $comment = strstr($comment, '*/', true);
  589. }
  590. return !empty($comment) ? ' /* ' . $comment . ' */' : '';
  591. }
  592. /**
  593. * distinct分析
  594. * @access protected
  595. * @param mixed $distinct
  596. * @return string
  597. */
  598. protected function parseDistinct($distinct)
  599. {
  600. return !empty($distinct) ? ' DISTINCT ' : '';
  601. }
  602. /**
  603. * union分析
  604. * @access protected
  605. * @param mixed $union
  606. * @return string
  607. */
  608. protected function parseUnion($union)
  609. {
  610. if (empty($union)) {
  611. return '';
  612. }
  613. $type = $union['type'];
  614. unset($union['type']);
  615. foreach ($union as $u) {
  616. if ($u instanceof \Closure) {
  617. $sql[] = $type . ' ' . $this->parseClosure($u);
  618. } elseif (is_string($u)) {
  619. $sql[] = $type . ' ( ' . $this->parseSqlTable($u) . ' )';
  620. }
  621. }
  622. return ' ' . implode(' ', $sql);
  623. }
  624. /**
  625. * index分析,可在操作链中指定需要强制使用的索引
  626. * @access protected
  627. * @param mixed $index
  628. * @return string
  629. */
  630. protected function parseForce($index)
  631. {
  632. if (empty($index)) {
  633. return '';
  634. }
  635. return sprintf(" FORCE INDEX ( %s ) ", is_array($index) ? implode(',', $index) : $index);
  636. }
  637. /**
  638. * 设置锁机制
  639. * @access protected
  640. * @param bool|string $lock
  641. * @return string
  642. */
  643. protected function parseLock($lock = false)
  644. {
  645. if (is_bool($lock)) {
  646. return $lock ? ' FOR UPDATE ' : '';
  647. } elseif (is_string($lock)) {
  648. return ' ' . trim($lock) . ' ';
  649. }
  650. }
  651. /**
  652. * 生成查询SQL
  653. * @access public
  654. * @param array $options 表达式
  655. * @return string
  656. */
  657. public function select($options = [])
  658. {
  659. $sql = str_replace(
  660. ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
  661. [
  662. $this->parseTable($options['table'], $options),
  663. $this->parseDistinct($options['distinct']),
  664. $this->parseField($options['field'], $options),
  665. $this->parseJoin($options['join'], $options),
  666. $this->parseWhere($options['where'], $options),
  667. $this->parseGroup($options['group']),
  668. $this->parseHaving($options['having']),
  669. $this->parseOrder($options['order'], $options),
  670. $this->parseLimit($options['limit']),
  671. $this->parseUnion($options['union']),
  672. $this->parseLock($options['lock']),
  673. $this->parseComment($options['comment']),
  674. $this->parseForce($options['force']),
  675. ], $this->selectSql);
  676. return $sql;
  677. }
  678. /**
  679. * 生成insert SQL
  680. * @access public
  681. * @param array $data 数据
  682. * @param array $options 表达式
  683. * @param bool $replace 是否replace
  684. * @return string
  685. */
  686. public function insert(array $data, $options = [], $replace = false)
  687. {
  688. // 分析并处理数据
  689. $data = $this->parseData($data, $options);
  690. if (empty($data)) {
  691. return 0;
  692. }
  693. $fields = array_keys($data);
  694. $values = array_values($data);
  695. $sql = str_replace(
  696. ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
  697. [
  698. $replace ? 'REPLACE' : 'INSERT',
  699. $this->parseTable($options['table'], $options),
  700. implode(' , ', $fields),
  701. implode(' , ', $values),
  702. $this->parseComment($options['comment']),
  703. ], $this->insertSql);
  704. return $sql;
  705. }
  706. /**
  707. * 生成insertall SQL
  708. * @access public
  709. * @param array $dataSet 数据集
  710. * @param array $options 表达式
  711. * @param bool $replace 是否replace
  712. * @return string
  713. * @throws Exception
  714. */
  715. public function insertAll($dataSet, $options = [], $replace = false)
  716. {
  717. // 获取合法的字段
  718. if ('*' == $options['field']) {
  719. $fields = array_keys($this->query->getFieldsType($options['table']));
  720. } else {
  721. $fields = $options['field'];
  722. }
  723. foreach ($dataSet as $data) {
  724. foreach ($data as $key => $val) {
  725. if (!in_array($key, $fields, true)) {
  726. if ($options['strict']) {
  727. throw new Exception('fields not exists:[' . $key . ']');
  728. }
  729. unset($data[$key]);
  730. } elseif (is_null($val)) {
  731. $data[$key] = 'NULL';
  732. } elseif (is_scalar($val)) {
  733. $data[$key] = $this->parseValue($val, $key);
  734. } elseif (is_object($val) && method_exists($val, '__toString')) {
  735. // 对象数据写入
  736. $data[$key] = $val->__toString();
  737. } else {
  738. // 过滤掉非标量数据
  739. unset($data[$key]);
  740. }
  741. }
  742. $value = array_values($data);
  743. $values[] = 'SELECT ' . implode(',', $value);
  744. if (!isset($insertFields)) {
  745. $insertFields = array_keys($data);
  746. }
  747. }
  748. foreach ($insertFields as $field) {
  749. $fields[] = $this->parseKey($field, $options, true);
  750. }
  751. return str_replace(
  752. ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
  753. [
  754. $replace ? 'REPLACE' : 'INSERT',
  755. $this->parseTable($options['table'], $options),
  756. implode(' , ', $insertFields),
  757. implode(' UNION ALL ', $values),
  758. $this->parseComment($options['comment']),
  759. ], $this->insertAllSql);
  760. }
  761. /**
  762. * 生成select insert SQL
  763. * @access public
  764. * @param array $fields 数据
  765. * @param string $table 数据表
  766. * @param array $options 表达式
  767. * @return string
  768. */
  769. public function selectInsert($fields, $table, $options)
  770. {
  771. if (is_string($fields)) {
  772. $fields = explode(',', $fields);
  773. }
  774. $fields = array_map([$this, 'parseKey'], $fields);
  775. $sql = 'INSERT INTO ' . $this->parseTable($table, $options) . ' (' . implode(',', $fields) . ') ' . $this->select($options);
  776. return $sql;
  777. }
  778. /**
  779. * 生成update SQL
  780. * @access public
  781. * @param array $data 数据
  782. * @param array $options 表达式
  783. * @return string
  784. */
  785. public function update($data, $options)
  786. {
  787. $table = $this->parseTable($options['table'], $options);
  788. $data = $this->parseData($data, $options);
  789. if (empty($data)) {
  790. return '';
  791. }
  792. foreach ($data as $key => $val) {
  793. $set[] = $key . '=' . $val;
  794. }
  795. $sql = str_replace(
  796. ['%TABLE%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  797. [
  798. $this->parseTable($options['table'], $options),
  799. implode(',', $set),
  800. $this->parseJoin($options['join'], $options),
  801. $this->parseWhere($options['where'], $options),
  802. $this->parseOrder($options['order'], $options),
  803. $this->parseLimit($options['limit']),
  804. $this->parseLock($options['lock']),
  805. $this->parseComment($options['comment']),
  806. ], $this->updateSql);
  807. return $sql;
  808. }
  809. /**
  810. * 生成delete SQL
  811. * @access public
  812. * @param array $options 表达式
  813. * @return string
  814. */
  815. public function delete($options)
  816. {
  817. $sql = str_replace(
  818. ['%TABLE%', '%USING%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  819. [
  820. $this->parseTable($options['table'], $options),
  821. !empty($options['using']) ? ' USING ' . $this->parseTable($options['using'], $options) . ' ' : '',
  822. $this->parseJoin($options['join'], $options),
  823. $this->parseWhere($options['where'], $options),
  824. $this->parseOrder($options['order'], $options),
  825. $this->parseLimit($options['limit']),
  826. $this->parseLock($options['lock']),
  827. $this->parseComment($options['comment']),
  828. ], $this->deleteSql);
  829. return $sql;
  830. }
  831. }