Builder.php 30 KB

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