Builder.php 32 KB

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