Builder.php 31 KB

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