Builder.php 31 KB

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