Builder.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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 ($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. }
  112. } elseif (is_scalar($val)) {
  113. // 过滤非标量数据
  114. if (0 === strpos($val, ':') && $this->query->isBind(substr($val, 1))) {
  115. $result[$item] = $val;
  116. } else {
  117. $key = str_replace('.', '_', $key);
  118. $this->query->bind('data__' . $key, $val, isset($bind[$key]) ? $bind[$key] : PDO::PARAM_STR);
  119. $result[$item] = ':data__' . $key;
  120. }
  121. }
  122. }
  123. return $result;
  124. }
  125. /**
  126. * 字段名分析
  127. * @access protected
  128. * @param string $key
  129. * @param array $options
  130. * @return string
  131. */
  132. protected function parseKey($key, $options = [], $strict = false)
  133. {
  134. return $key;
  135. }
  136. /**
  137. * value分析
  138. * @access protected
  139. * @param mixed $value
  140. * @param string $field
  141. * @return string|array
  142. */
  143. protected function parseValue($value, $field = '')
  144. {
  145. if (is_string($value)) {
  146. $value = strpos($value, ':') === 0 && $this->query->isBind(substr($value, 1)) ? $value : $this->connection->quote($value);
  147. } elseif (is_array($value)) {
  148. $value = array_map([$this, 'parseValue'], $value);
  149. } elseif (is_bool($value)) {
  150. $value = $value ? '1' : '0';
  151. } elseif (is_null($value)) {
  152. $value = 'null';
  153. }
  154. return $value;
  155. }
  156. /**
  157. * field分析
  158. * @access protected
  159. * @param mixed $fields
  160. * @param array $options
  161. * @return string
  162. */
  163. protected function parseField($fields, $options = [])
  164. {
  165. if ('*' == $fields || empty($fields)) {
  166. $fieldsStr = '*';
  167. } elseif (is_array($fields)) {
  168. // 支持 'field1'=>'field2' 这样的字段别名定义
  169. $array = [];
  170. foreach ($fields as $key => $field) {
  171. if ($field instanceof Expression) {
  172. $array[] = $field->getValue();
  173. } elseif (!is_numeric($key)) {
  174. $array[] = $this->parseKey($key, $options) . ' AS ' . $this->parseKey($field, $options, true);
  175. } else {
  176. $array[] = $this->parseKey($field, $options);
  177. }
  178. }
  179. $fieldsStr = implode(',', $array);
  180. }
  181. return $fieldsStr;
  182. }
  183. /**
  184. * table分析
  185. * @access protected
  186. * @param mixed $tables
  187. * @param array $options
  188. * @return string
  189. */
  190. protected function parseTable($tables, $options = [])
  191. {
  192. $item = [];
  193. foreach ((array) $tables as $key => $table) {
  194. if (!is_numeric($key)) {
  195. $key = $this->parseSqlTable($key);
  196. $item[] = $this->parseKey($key) . ' ' . (isset($options['alias'][$table]) ? $this->parseKey($options['alias'][$table]) : $this->parseKey($table));
  197. } else {
  198. $table = $this->parseSqlTable($table);
  199. if (isset($options['alias'][$table])) {
  200. $item[] = $this->parseKey($table) . ' ' . $this->parseKey($options['alias'][$table]);
  201. } else {
  202. $item[] = $this->parseKey($table);
  203. }
  204. }
  205. }
  206. return implode(',', $item);
  207. }
  208. /**
  209. * where分析
  210. * @access protected
  211. * @param mixed $where 查询条件
  212. * @param array $options 查询参数
  213. * @return string
  214. */
  215. protected function parseWhere($where, $options)
  216. {
  217. $whereStr = $this->buildWhere($where, $options);
  218. if (!empty($options['soft_delete'])) {
  219. // 附加软删除条件
  220. list($field, $condition) = $options['soft_delete'];
  221. $binds = $this->query->getFieldsBind($options['table']);
  222. $whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : '';
  223. $whereStr = $whereStr . $this->parseWhereItem($field, $condition, '', $options, $binds);
  224. }
  225. return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
  226. }
  227. /**
  228. * 生成查询条件SQL
  229. * @access public
  230. * @param mixed $where
  231. * @param array $options
  232. * @return string
  233. */
  234. public function buildWhere($where, $options)
  235. {
  236. if (empty($where)) {
  237. $where = [];
  238. }
  239. if ($where instanceof Query) {
  240. return $this->buildWhere($where->getOptions('where'), $options);
  241. }
  242. $whereStr = '';
  243. $binds = $this->query->getFieldsBind($options['table']);
  244. foreach ($where as $key => $val) {
  245. $str = [];
  246. foreach ($val as $field => $value) {
  247. if ($value instanceof Expression) {
  248. $str[] = ' ' . $key . ' ( ' . $value->getValue() . ' )';
  249. continue;
  250. }
  251. if ($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 (strpos($val, '=')) {
  510. list($val1, $val2) = explode('=', $val, 2);
  511. $condition[] = $this->parseKey($val1, $options) . '=' . $this->parseKey($val2, $options);
  512. } else {
  513. $condition[] = $val;
  514. }
  515. }
  516. $table = $this->parseTable($table, $options);
  517. $joinStr .= ' ' . $type . ' JOIN ' . $table . ' ON ' . implode(' AND ', $condition);
  518. }
  519. }
  520. return $joinStr;
  521. }
  522. /**
  523. * order分析
  524. * @access protected
  525. * @param mixed $order
  526. * @param array $options 查询条件
  527. * @return string
  528. */
  529. protected function parseOrder($order, $options = [])
  530. {
  531. if (empty($order)) {
  532. return '';
  533. }
  534. $array = [];
  535. foreach ($order as $key => $val) {
  536. if ($val instanceof Expression) {
  537. $array[] = $val->getValue();
  538. } elseif ('[rand]' == $val) {
  539. $array[] = $this->parseRand();
  540. } else {
  541. if (is_numeric($key)) {
  542. list($key, $sort) = explode(' ', strpos($val, ' ') ? $val : $val . ' ');
  543. } else {
  544. $sort = $val;
  545. }
  546. $sort = strtoupper($sort);
  547. $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
  548. $array[] = $this->parseKey($key, $options, true) . $sort;
  549. }
  550. }
  551. $order = implode(',', $array);
  552. return !empty($order) ? ' ORDER BY ' . $order : '';
  553. }
  554. /**
  555. * group分析
  556. * @access protected
  557. * @param mixed $group
  558. * @return string
  559. */
  560. protected function parseGroup($group)
  561. {
  562. return !empty($group) ? ' GROUP BY ' . $this->parseKey($group) : '';
  563. }
  564. /**
  565. * having分析
  566. * @access protected
  567. * @param string $having
  568. * @return string
  569. */
  570. protected function parseHaving($having)
  571. {
  572. return !empty($having) ? ' HAVING ' . $having : '';
  573. }
  574. /**
  575. * comment分析
  576. * @access protected
  577. * @param string $comment
  578. * @return string
  579. */
  580. protected function parseComment($comment)
  581. {
  582. if (false !== strpos($comment, '*/')) {
  583. $comment = strstr($coment, '*/', true);
  584. }
  585. return !empty($comment) ? ' /* ' . $comment . ' */' : '';
  586. }
  587. /**
  588. * distinct分析
  589. * @access protected
  590. * @param mixed $distinct
  591. * @return string
  592. */
  593. protected function parseDistinct($distinct)
  594. {
  595. return !empty($distinct) ? ' DISTINCT ' : '';
  596. }
  597. /**
  598. * union分析
  599. * @access protected
  600. * @param mixed $union
  601. * @return string
  602. */
  603. protected function parseUnion($union)
  604. {
  605. if (empty($union)) {
  606. return '';
  607. }
  608. $type = $union['type'];
  609. unset($union['type']);
  610. foreach ($union as $u) {
  611. if ($u instanceof \Closure) {
  612. $sql[] = $type . ' ' . $this->parseClosure($u);
  613. } elseif (is_string($u)) {
  614. $sql[] = $type . ' ( ' . $this->parseSqlTable($u) . ' )';
  615. }
  616. }
  617. return ' ' . implode(' ', $sql);
  618. }
  619. /**
  620. * index分析,可在操作链中指定需要强制使用的索引
  621. * @access protected
  622. * @param mixed $index
  623. * @return string
  624. */
  625. protected function parseForce($index)
  626. {
  627. if (empty($index)) {
  628. return '';
  629. }
  630. return sprintf(" FORCE INDEX ( %s ) ", is_array($index) ? implode(',', $index) : $index);
  631. }
  632. /**
  633. * 设置锁机制
  634. * @access protected
  635. * @param bool|string $lock
  636. * @return string
  637. */
  638. protected function parseLock($lock = false)
  639. {
  640. if (is_bool($lock)) {
  641. return $lock ? ' FOR UPDATE ' : '';
  642. } elseif (is_string($lock)) {
  643. return ' ' . trim($lock) . ' ';
  644. }
  645. }
  646. /**
  647. * 生成查询SQL
  648. * @access public
  649. * @param array $options 表达式
  650. * @return string
  651. */
  652. public function select($options = [])
  653. {
  654. $sql = str_replace(
  655. ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
  656. [
  657. $this->parseTable($options['table'], $options),
  658. $this->parseDistinct($options['distinct']),
  659. $this->parseField($options['field'], $options),
  660. $this->parseJoin($options['join'], $options),
  661. $this->parseWhere($options['where'], $options),
  662. $this->parseGroup($options['group']),
  663. $this->parseHaving($options['having']),
  664. $this->parseOrder($options['order'], $options),
  665. $this->parseLimit($options['limit']),
  666. $this->parseUnion($options['union']),
  667. $this->parseLock($options['lock']),
  668. $this->parseComment($options['comment']),
  669. $this->parseForce($options['force']),
  670. ], $this->selectSql);
  671. return $sql;
  672. }
  673. /**
  674. * 生成insert SQL
  675. * @access public
  676. * @param array $data 数据
  677. * @param array $options 表达式
  678. * @param bool $replace 是否replace
  679. * @return string
  680. */
  681. public function insert(array $data, $options = [], $replace = false)
  682. {
  683. // 分析并处理数据
  684. $data = $this->parseData($data, $options);
  685. if (empty($data)) {
  686. return 0;
  687. }
  688. $fields = array_keys($data);
  689. $values = array_values($data);
  690. $sql = str_replace(
  691. ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
  692. [
  693. $replace ? 'REPLACE' : 'INSERT',
  694. $this->parseTable($options['table'], $options),
  695. implode(' , ', $fields),
  696. implode(' , ', $values),
  697. $this->parseComment($options['comment']),
  698. ], $this->insertSql);
  699. return $sql;
  700. }
  701. /**
  702. * 生成insertall SQL
  703. * @access public
  704. * @param array $dataSet 数据集
  705. * @param array $options 表达式
  706. * @param bool $replace 是否replace
  707. * @return string
  708. * @throws Exception
  709. */
  710. public function insertAll($dataSet, $options = [], $replace = false)
  711. {
  712. // 获取合法的字段
  713. if ('*' == $options['field']) {
  714. $fields = array_keys($this->query->getFieldsType($options['table']));
  715. } else {
  716. $fields = $options['field'];
  717. }
  718. foreach ($dataSet as $data) {
  719. foreach ($data as $key => $val) {
  720. if (!in_array($key, $fields, true)) {
  721. if ($options['strict']) {
  722. throw new Exception('fields not exists:[' . $key . ']');
  723. }
  724. unset($data[$key]);
  725. } elseif (is_null($val)) {
  726. $data[$key] = 'NULL';
  727. } elseif (is_scalar($val)) {
  728. $data[$key] = $this->parseValue($val, $key);
  729. } elseif (is_object($val) && method_exists($val, '__toString')) {
  730. // 对象数据写入
  731. $data[$key] = $val->__toString();
  732. } else {
  733. // 过滤掉非标量数据
  734. unset($data[$key]);
  735. }
  736. }
  737. $value = array_values($data);
  738. $values[] = 'SELECT ' . implode(',', $value);
  739. if (!isset($insertFields)) {
  740. $insertFields = array_keys($data);
  741. }
  742. }
  743. foreach ($insertFields as $field) {
  744. $fields[] = $this->parseKey($query, $field, true);
  745. }
  746. return str_replace(
  747. ['%INSERT%', '%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'],
  748. [
  749. $replace ? 'REPLACE' : 'INSERT',
  750. $this->parseTable($options['table'], $options),
  751. implode(' , ', $insertFields),
  752. implode(' UNION ALL ', $values),
  753. $this->parseComment($options['comment']),
  754. ], $this->insertAllSql);
  755. }
  756. /**
  757. * 生成select insert SQL
  758. * @access public
  759. * @param array $fields 数据
  760. * @param string $table 数据表
  761. * @param array $options 表达式
  762. * @return string
  763. */
  764. public function selectInsert($fields, $table, $options)
  765. {
  766. if (is_string($fields)) {
  767. $fields = explode(',', $fields);
  768. }
  769. $fields = array_map([$this, 'parseKey'], $fields);
  770. $sql = 'INSERT INTO ' . $this->parseTable($table, $options) . ' (' . implode(',', $fields) . ') ' . $this->select($options);
  771. return $sql;
  772. }
  773. /**
  774. * 生成update SQL
  775. * @access public
  776. * @param array $data 数据
  777. * @param array $options 表达式
  778. * @return string
  779. */
  780. public function update($data, $options)
  781. {
  782. $table = $this->parseTable($options['table'], $options);
  783. $data = $this->parseData($data, $options);
  784. if (empty($data)) {
  785. return '';
  786. }
  787. foreach ($data as $key => $val) {
  788. $set[] = $key . '=' . $val;
  789. }
  790. $sql = str_replace(
  791. ['%TABLE%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  792. [
  793. $this->parseTable($options['table'], $options),
  794. implode(',', $set),
  795. $this->parseJoin($options['join'], $options),
  796. $this->parseWhere($options['where'], $options),
  797. $this->parseOrder($options['order'], $options),
  798. $this->parseLimit($options['limit']),
  799. $this->parseLock($options['lock']),
  800. $this->parseComment($options['comment']),
  801. ], $this->updateSql);
  802. return $sql;
  803. }
  804. /**
  805. * 生成delete SQL
  806. * @access public
  807. * @param array $options 表达式
  808. * @return string
  809. */
  810. public function delete($options)
  811. {
  812. $sql = str_replace(
  813. ['%TABLE%', '%USING%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'],
  814. [
  815. $this->parseTable($options['table'], $options),
  816. !empty($options['using']) ? ' USING ' . $this->parseTable($options['using'], $options) . ' ' : '',
  817. $this->parseJoin($options['join'], $options),
  818. $this->parseWhere($options['where'], $options),
  819. $this->parseOrder($options['order'], $options),
  820. $this->parseLimit($options['limit']),
  821. $this->parseLock($options['lock']),
  822. $this->parseComment($options['comment']),
  823. ], $this->deleteSql);
  824. return $sql;
  825. }
  826. }