Builder.php 31 KB

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