Builder.php 29 KB

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