Builder.php 30 KB

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