Builder.php 32 KB

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