Builder.php 31 KB

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