Builder.php 32 KB

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