Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1298 řádky
43 KiB

před 3 roky
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 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\Config;
  14. use Think\Debug;
  15. abstract class Driver
  16. {
  17. // PDO操作实例
  18. protected $PDOStatement = null;
  19. // 当前操作所属的模型名
  20. protected $model = '_think_';
  21. // 当前SQL指令
  22. protected $queryStr = '';
  23. protected $modelSql = array();
  24. // 最后插入ID
  25. protected $lastInsID = null;
  26. // 返回或者影响记录数
  27. protected $numRows = 0;
  28. // 事物操作PDO实例
  29. protected $transPDO = null;
  30. // 事务指令数
  31. protected $transTimes = 0;
  32. // 错误信息
  33. protected $error = '';
  34. // 数据库连接ID 支持多个连接
  35. protected $linkID = array();
  36. // 当前连接ID
  37. protected $_linkID = null;
  38. // 数据库连接参数配置
  39. protected $config = array(
  40. 'type' => '', // 数据库类型
  41. 'hostname' => '127.0.0.1', // 服务器地址
  42. 'database' => '', // 数据库名
  43. 'username' => '', // 用户名
  44. 'password' => '', // 密码
  45. 'hostport' => '', // 端口
  46. 'dsn' => '', //
  47. 'params' => array(), // 数据库连接参数
  48. 'charset' => 'utf8', // 数据库编码默认采用utf8
  49. 'prefix' => '', // 数据库表前缀
  50. 'debug' => false, // 数据库调试模式
  51. 'deploy' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
  52. 'rw_separate' => false, // 数据库读写是否分离 主从式有效
  53. 'master_num' => 1, // 读写分离后 主服务器数量
  54. 'slave_no' => '', // 指定从服务器序号
  55. 'db_like_fields' => '',
  56. );
  57. // 数据库表达式
  58. protected $exp = array('eq' => '=', 'neq' => '<>', 'gt' => '>', 'egt' => '>=', 'lt' => '<', 'elt' => '<=', 'notlike' => 'NOT LIKE', 'like' => 'LIKE', 'in' => 'IN', 'notin' => 'NOT IN', 'not in' => 'NOT IN', 'between' => 'BETWEEN', 'not between' => 'NOT BETWEEN', 'notbetween' => 'NOT BETWEEN');
  59. // 查询表达式
  60. protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';
  61. // 查询次数
  62. protected $queryTimes = 0;
  63. // 执行次数
  64. protected $executeTimes = 0;
  65. // PDO连接参数
  66. protected $options = array(
  67. PDO::ATTR_CASE => PDO::CASE_LOWER,
  68. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  69. PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
  70. PDO::ATTR_STRINGIFY_FETCHES => false,
  71. );
  72. protected $bind = array(); // 参数绑定
  73. /**
  74. * 架构函数 读取数据库配置信息
  75. * @access public
  76. * @param array $config 数据库配置数组
  77. */
  78. public function __construct($config = '')
  79. {
  80. if (!empty($config)) {
  81. $this->config = array_merge($this->config, $config);
  82. if (is_array($this->config['params'])) {
  83. $this->options = $this->config['params'] + $this->options;
  84. }
  85. }
  86. }
  87. /**
  88. * 连接数据库方法
  89. * @access public
  90. */
  91. public function connect($config = '', $linkNum = 0, $autoConnection = false)
  92. {
  93. if (!isset($this->linkID[$linkNum])) {
  94. if (empty($config)) {
  95. $config = $this->config;
  96. }
  97. try {
  98. if (empty($config['dsn'])) {
  99. $config['dsn'] = $this->parseDsn($config);
  100. }
  101. if (version_compare(PHP_VERSION, '5.3.6', '<=')) {
  102. // 禁用模拟预处理语句
  103. $this->options[PDO::ATTR_EMULATE_PREPARES] = false;
  104. }
  105. $this->linkID[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $this->options);
  106. } catch (\PDOException $e) {
  107. if ($autoConnection) {
  108. trace($e->getMessage(), '', 'ERR');
  109. return $this->connect($autoConnection, $linkNum);
  110. } elseif ($config['debug']) {
  111. E($e->getMessage());
  112. }
  113. }
  114. }
  115. return $this->linkID[$linkNum];
  116. }
  117. /**
  118. * 解析pdo连接的dsn信息
  119. * @access public
  120. * @param array $config 连接信息
  121. * @return string
  122. */
  123. protected function parseDsn($config)
  124. {}
  125. /**
  126. * 释放查询结果
  127. * @access public
  128. */
  129. public function free()
  130. {
  131. $this->PDOStatement = null;
  132. }
  133. /**
  134. * 执行查询 返回数据集
  135. * @access public
  136. * @param string $str sql指令
  137. * @param boolean $fetchSql 不执行只是获取SQL
  138. * @param boolean $master 是否在主服务器读操作
  139. * @return mixed
  140. */
  141. public function query($str, $fetchSql = false, $master = false)
  142. {
  143. $this->initConnect($master);
  144. if (!$this->_linkID) {
  145. return false;
  146. }
  147. $this->queryStr = $str;
  148. if (!empty($this->bind)) {
  149. $that = $this;
  150. $this->queryStr = strtr($this->queryStr, array_map(function ($val) use ($that) {return '\'' . $that->escapeString($val) . '\'';}, $this->bind));
  151. }
  152. if ($fetchSql) {
  153. return $this->queryStr;
  154. }
  155. //释放前次的查询结果
  156. if (!empty($this->PDOStatement)) {
  157. $this->free();
  158. }
  159. $this->queryTimes++;
  160. N('db_query', 1); // 兼容代码
  161. // 调试开始
  162. $this->debug(true);
  163. $this->PDOStatement = $this->_linkID->prepare($str);
  164. if (false === $this->PDOStatement) {
  165. $this->error();
  166. return false;
  167. }
  168. foreach ($this->bind as $key => $val) {
  169. if (is_array($val)) {
  170. $this->PDOStatement->bindValue($key, $val[0], $val[1]);
  171. } else {
  172. $this->PDOStatement->bindValue($key, $val);
  173. }
  174. }
  175. $this->bind = array();
  176. try {
  177. $result = $this->PDOStatement->execute();
  178. // 调试结束
  179. $this->debug(false);
  180. if (false === $result) {
  181. $this->error();
  182. return false;
  183. } else {
  184. return $this->getResult();
  185. }
  186. } catch (\PDOException $e) {
  187. $this->error();
  188. return false;
  189. }
  190. }
  191. /**
  192. * 执行语句
  193. * @access public
  194. * @param string $str sql指令
  195. * @param boolean $fetchSql 不执行只是获取SQL
  196. * @return mixed
  197. */
  198. public function execute($str, $fetchSql = false)
  199. {
  200. $this->initConnect(true);
  201. if (!$this->_linkID) {
  202. return false;
  203. }
  204. $this->queryStr = $str;
  205. if (!empty($this->bind)) {
  206. $that = $this;
  207. $this->queryStr = strtr($this->queryStr, array_map(function ($val) use ($that) {return '\'' . $that->escapeString($val) . '\'';}, $this->bind));
  208. }
  209. if ($fetchSql) {
  210. return $this->queryStr;
  211. }
  212. //释放前次的查询结果
  213. if (!empty($this->PDOStatement)) {
  214. $this->free();
  215. }
  216. $this->executeTimes++;
  217. N('db_write', 1); // 兼容代码
  218. // 记录开始执行时间
  219. $this->debug(true);
  220. $this->PDOStatement = $this->_linkID->prepare($str);
  221. if (false === $this->PDOStatement) {
  222. $this->error();
  223. return false;
  224. }
  225. foreach ($this->bind as $key => $val) {
  226. if (is_array($val)) {
  227. $this->PDOStatement->bindValue($key, $val[0], $val[1]);
  228. } else {
  229. $this->PDOStatement->bindValue($key, $val);
  230. }
  231. }
  232. $this->bind = array();
  233. try {
  234. $result = $this->PDOStatement->execute();
  235. // 调试结束
  236. $this->debug(false);
  237. if (false === $result) {
  238. $this->error();
  239. return false;
  240. } else {
  241. $this->numRows = $this->PDOStatement->rowCount();
  242. if (preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
  243. $this->lastInsID = $this->_linkID->lastInsertId();
  244. }
  245. return $this->numRows;
  246. }
  247. } catch (\PDOException $e) {
  248. $this->error();
  249. return false;
  250. }
  251. }
  252. /**
  253. * 启动事务
  254. * @access public
  255. * @return void
  256. */
  257. public function startTrans()
  258. {
  259. $this->initConnect(true);
  260. if (!$this->_linkID) {
  261. return false;
  262. }
  263. //数据rollback 支持
  264. if (0 == $this->transTimes) {
  265. // 记录当前操作PDO
  266. $this->transPdo = $this->_linkID;
  267. $this->_linkID->beginTransaction();
  268. }
  269. $this->transTimes++;
  270. return;
  271. }
  272. /**
  273. * 用于非自动提交状态下面的查询提交
  274. * @access public
  275. * @return boolean
  276. */
  277. public function commit()
  278. {
  279. if (1 == $this->transTimes) {
  280. // 由嵌套事物的最外层进行提交
  281. $result = $this->_linkID->commit();
  282. $this->transTimes = 0;
  283. $this->transPdo = null;
  284. if (!$result) {
  285. $this->error();
  286. return false;
  287. }
  288. } else {
  289. $this->transTimes = $this->transTimes <= 0 ? 0 : $this->transTimes - 1;
  290. }
  291. return true;
  292. }
  293. /**
  294. * 事务回滚
  295. * @access public
  296. * @return boolean
  297. */
  298. public function rollback()
  299. {
  300. if ($this->transTimes > 0) {
  301. $result = $this->_linkID->rollback();
  302. $this->transTimes = 0;
  303. $this->transPdo = null;
  304. if (!$result) {
  305. $this->error();
  306. return false;
  307. }
  308. }
  309. return true;
  310. }
  311. /**
  312. * 获得所有的查询数据
  313. * @access private
  314. * @return array
  315. */
  316. private function getResult()
  317. {
  318. //返回数据集
  319. $result = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
  320. $this->numRows = count($result);
  321. return $result;
  322. }
  323. /**
  324. * 获得查询次数
  325. * @access public
  326. * @param boolean $execute 是否包含所有查询
  327. * @return integer
  328. */
  329. public function getQueryTimes($execute = false)
  330. {
  331. return $execute ? $this->queryTimes + $this->executeTimes : $this->queryTimes;
  332. }
  333. /**
  334. * 获得执行次数
  335. * @access public
  336. * @return integer
  337. */
  338. public function getExecuteTimes()
  339. {
  340. return $this->executeTimes;
  341. }
  342. /**
  343. * 关闭数据库
  344. * @access public
  345. */
  346. public function close()
  347. {
  348. $this->_linkID = null;
  349. }
  350. /**
  351. * 数据库错误信息
  352. * 并显示当前的SQL语句
  353. * @access public
  354. * @return string
  355. */
  356. public function error()
  357. {
  358. if ($this->PDOStatement) {
  359. $error = $this->PDOStatement->errorInfo();
  360. $this->error = $error[1] . ':' . $error[2];
  361. } else {
  362. $this->error = '';
  363. }
  364. if ('' != $this->queryStr) {
  365. $this->error .= "\n [ SQL语句 ] : " . $this->queryStr;
  366. }
  367. // 记录错误日志
  368. trace($this->error, '', 'ERR');
  369. if ($this->config['debug']) {
  370. // 开启数据库调试模式
  371. E($this->error);
  372. } else {
  373. return $this->error;
  374. }
  375. }
  376. /**
  377. * 设置锁机制
  378. * @access protected
  379. * @return string
  380. */
  381. protected function parseLock($lock = false)
  382. {
  383. return $lock ? ' FOR UPDATE ' : '';
  384. }
  385. /**
  386. * set分析
  387. * @access protected
  388. * @param array $data
  389. * @return string
  390. */
  391. protected function parseSet($data)
  392. {
  393. foreach ($data as $key => $val) {
  394. if (isset($val[0]) && 'exp' == $val[0]) {
  395. $set[] = $this->parseKey($key) . '=' . $val[1];
  396. } elseif (is_null($val)) {
  397. $set[] = $this->parseKey($key) . '=NULL';
  398. } elseif (is_scalar($val)) {
  399. // 过滤非标量数据
  400. if (0 === strpos($val, ':') && in_array($val, array_keys($this->bind))) {
  401. $set[] = $this->parseKey($key) . '=' . $val;
  402. } else {
  403. $name = count($this->bind);
  404. $set[] = $this->parseKey($key) . '=:' . $key . '_' . $name;
  405. $this->bindParam($key . '_' . $name, $val);
  406. }
  407. }
  408. }
  409. return ' SET ' . implode(',', $set);
  410. }
  411. /**
  412. * 参数绑定
  413. * @access protected
  414. * @param string $name 绑定参数名
  415. * @param mixed $value 绑定值
  416. * @return void
  417. */
  418. protected function bindParam($name, $value)
  419. {
  420. $this->bind[':' . $name] = $value;
  421. }
  422. /**
  423. * 字段和表名处理
  424. * @access public
  425. * @param string $key
  426. * @param bool $strict
  427. * @return string
  428. */
  429. public function parseKey($key, $strict = false)
  430. {
  431. return $key;
  432. }
  433. /**
  434. * value分析
  435. * @access protected
  436. * @param mixed $value
  437. * @return string
  438. */
  439. protected function parseValue($value)
  440. {
  441. if (is_string($value)) {
  442. $value = strpos($value, ':') === 0 && in_array($value, array_keys($this->bind)) ? $this->escapeString($value) : '\'' . $this->escapeString($value) . '\'';
  443. } elseif (isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp') {
  444. $value = $this->escapeString($value[1]);
  445. } elseif (is_array($value)) {
  446. $value = array_map(array($this, 'parseValue'), $value);
  447. } elseif (is_bool($value)) {
  448. $value = $value ? '1' : '0';
  449. } elseif (is_null($value)) {
  450. $value = 'null';
  451. }
  452. return $value;
  453. }
  454. /**
  455. * field分析
  456. * @access protected
  457. * @param mixed $fields
  458. * @return string
  459. */
  460. protected function parseField($fields)
  461. {
  462. if (is_string($fields) && '' !== $fields) {
  463. $fields = explode(',', $fields);
  464. }
  465. if (is_array($fields)) {
  466. // 完善数组方式传字段名的支持
  467. // 支持 'field1'=>'field2' 这样的字段别名定义
  468. $array = array();
  469. foreach ($fields as $key => $field) {
  470. if (!is_numeric($key)) {
  471. $array[] = $this->parseKey($key) . ' AS ' . $this->parseKey($field);
  472. } else {
  473. $array[] = $this->parseKey($field);
  474. }
  475. }
  476. $fieldsStr = implode(',', $array);
  477. } else {
  478. $fieldsStr = '*';
  479. }
  480. //TODO 如果是查询全部字段,并且是join的方式,那么就把要查的表加个别名,以免字段被覆盖
  481. return $fieldsStr;
  482. }
  483. /**
  484. * table分析
  485. * @access protected
  486. * @param mixed $table
  487. * @return string
  488. */
  489. protected function parseTable($tables)
  490. {
  491. if (is_array($tables)) {
  492. // 支持别名定义
  493. $array = array();
  494. foreach ($tables as $table => $alias) {
  495. if (!is_numeric($table)) {
  496. $array[] = $this->parseKey($table) . ' ' . $this->parseKey($alias);
  497. } else {
  498. $array[] = $this->parseKey($alias);
  499. }
  500. }
  501. $tables = $array;
  502. } elseif (is_string($tables)) {
  503. $tables = array_map(array($this, 'parseKey'), explode(',', $tables));
  504. }
  505. return implode(',', $tables);
  506. }
  507. /**
  508. * where分析
  509. * @access protected
  510. * @param mixed $where
  511. * @return string
  512. */
  513. protected function parseWhere($where)
  514. {
  515. $whereStr = '';
  516. if (is_string($where)) {
  517. // 直接使用字符串条件
  518. $whereStr = $where;
  519. } else {
  520. // 使用数组表达式
  521. $operate = isset($where['_logic']) ? strtoupper($where['_logic']) : '';
  522. if (in_array($operate, array('AND', 'OR', 'XOR'))) {
  523. // 定义逻辑运算规则 例如 OR XOR AND NOT
  524. $operate = ' ' . $operate . ' ';
  525. unset($where['_logic']);
  526. } else {
  527. // 默认进行 AND 运算
  528. $operate = ' AND ';
  529. }
  530. foreach ($where as $key => $val) {
  531. if (is_numeric($key)) {
  532. $key = '_complex';
  533. }
  534. if (0 === strpos($key, '_')) {
  535. // 解析特殊条件表达式
  536. $whereStr .= $this->parseThinkWhere($key, $val);
  537. } else {
  538. // 查询字段的安全过滤
  539. // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
  540. // E(L('_EXPRESS_ERROR_').':'.$key);
  541. // }
  542. // 多条件支持
  543. $multi = is_array($val) && isset($val['_multi']);
  544. $key = trim($key);
  545. if (strpos($key, '|')) {
  546. // 支持 name|title|nickname 方式定义查询字段
  547. $array = explode('|', $key);
  548. $str = array();
  549. foreach ($array as $m => $k) {
  550. $v = $multi ? $val[$m] : $val;
  551. $str[] = $this->parseWhereItem($this->parseKey($k), $v);
  552. }
  553. $whereStr .= '( ' . implode(' OR ', $str) . ' )';
  554. } elseif (strpos($key, '&')) {
  555. $array = explode('&', $key);
  556. $str = array();
  557. foreach ($array as $m => $k) {
  558. $v = $multi ? $val[$m] : $val;
  559. $str[] = '(' . $this->parseWhereItem($this->parseKey($k), $v) . ')';
  560. }
  561. $whereStr .= '( ' . implode(' AND ', $str) . ' )';
  562. } else {
  563. $whereStr .= $this->parseWhereItem($this->parseKey($key), $val);
  564. }
  565. }
  566. $whereStr .= $operate;
  567. }
  568. $whereStr = substr($whereStr, 0, -strlen($operate));
  569. }
  570. return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
  571. }
  572. // where子单元分析
  573. protected function parseWhereItem($key, $val)
  574. {
  575. $whereStr = '';
  576. if (is_array($val)) {
  577. if (is_string($val[0])) {
  578. $exp = strtolower($val[0]);
  579. if (preg_match('/^(eq|neq|gt|egt|lt|elt)$/', $exp)) {
  580. // 比较运算
  581. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($val[1]);
  582. } elseif (preg_match('/^(notlike|like)$/', $exp)) {
  583. // 模糊查找
  584. if (is_array($val[1])) {
  585. $likeLogic = isset($val[2]) ? strtoupper($val[2]) : 'OR';
  586. if (in_array($likeLogic, array('AND', 'OR', 'XOR'))) {
  587. $like = array();
  588. foreach ($val[1] as $item) {
  589. $like[] = $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($item);
  590. }
  591. $whereStr .= '(' . implode(' ' . $likeLogic . ' ', $like) . ')';
  592. }
  593. } else {
  594. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($val[1]);
  595. }
  596. } elseif ('bind' == $exp) {
  597. // 使用表达式
  598. $whereStr .= $key . ' = :' . $val[1];
  599. } elseif ('exp' == $exp) {
  600. // 使用表达式
  601. $whereStr .= $key . ' ' . $val[1];
  602. } elseif (preg_match('/^(notin|not in|in)$/', $exp)) {
  603. // IN 运算
  604. if (isset($val[2]) && 'exp' == $val[2]) {
  605. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $val[1];
  606. } else {
  607. if (is_string($val[1])) {
  608. $val[1] = explode(',', $val[1]);
  609. }
  610. $zone = implode(',', $this->parseValue($val[1]));
  611. $whereStr .= $key . ' ' . $this->exp[$exp] . ' (' . $zone . ')';
  612. }
  613. } elseif (preg_match('/^(notbetween|not between|between)$/', $exp)) {
  614. // BETWEEN运算
  615. $data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
  616. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($data[0]) . ' AND ' . $this->parseValue($data[1]);
  617. } else {
  618. E(L('_EXPRESS_ERROR_') . ':' . $val[0]);
  619. }
  620. } else {
  621. $count = count($val);
  622. $rule = isset($val[$count - 1]) ? (is_array($val[$count - 1]) ? strtoupper($val[$count - 1][0]) : strtoupper($val[$count - 1])) : '';
  623. if (in_array($rule, array('AND', 'OR', 'XOR'))) {
  624. $count = $count - 1;
  625. } else {
  626. $rule = 'AND';
  627. }
  628. for ($i = 0; $i < $count; $i++) {
  629. $data = is_array($val[$i]) ? $val[$i][1] : $val[$i];
  630. if ('exp' == strtolower($val[$i][0])) {
  631. $whereStr .= $key . ' ' . $data . ' ' . $rule . ' ';
  632. } else {
  633. $whereStr .= $this->parseWhereItem($key, $val[$i]) . ' ' . $rule . ' ';
  634. }
  635. }
  636. $whereStr = '( ' . substr($whereStr, 0, -4) . ' )';
  637. }
  638. } else {
  639. //对字符串类型字段采用模糊匹配
  640. $likeFields = $this->config['db_like_fields'];
  641. if ($likeFields && preg_match('/^(' . $likeFields . ')$/i', $key)) {
  642. $whereStr .= $key . ' LIKE ' . $this->parseValue('%' . $val . '%');
  643. } else {
  644. $whereStr .= $key . ' = ' . $this->parseValue($val);
  645. }
  646. }
  647. return $whereStr;
  648. }
  649. /**
  650. * 特殊条件分析
  651. * @access protected
  652. * @param string $key
  653. * @param mixed $val
  654. * @return string
  655. */
  656. protected function parseThinkWhere($key, $val)
  657. {
  658. $whereStr = '';
  659. switch ($key) {
  660. case '_string':
  661. // 字符串模式查询条件
  662. $whereStr = $val;
  663. break;
  664. case '_complex':
  665. // 复合查询条件
  666. $whereStr = substr($this->parseWhere($val), 6);
  667. break;
  668. case '_query':
  669. // 字符串模式查询条件
  670. parse_str($val, $where);
  671. if (isset($where['_logic'])) {
  672. $op = ' ' . strtoupper($where['_logic']) . ' ';
  673. unset($where['_logic']);
  674. } else {
  675. $op = ' AND ';
  676. }
  677. $array = array();
  678. foreach ($where as $field => $data) {
  679. $array[] = $this->parseKey($field) . ' = ' . $this->parseValue($data);
  680. }
  681. $whereStr = implode($op, $array);
  682. break;
  683. }
  684. return '( ' . $whereStr . ' )';
  685. }
  686. /**
  687. * limit分析
  688. * @access protected
  689. * @param mixed $lmit
  690. * @return string
  691. */
  692. protected function parseLimit($limit)
  693. {
  694. return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
  695. }
  696. /**
  697. * join分析
  698. * @access protected
  699. * @param mixed $join
  700. * @return string
  701. */
  702. protected function parseJoin($join)
  703. {
  704. $joinStr = '';
  705. if (!empty($join)) {
  706. $joinStr = ' ' . implode(' ', $join) . ' ';
  707. }
  708. return $joinStr;
  709. }
  710. /**
  711. * order分析
  712. * @access protected
  713. * @param mixed $order
  714. * @return string
  715. */
  716. protected function parseOrder($order)
  717. {
  718. if (empty($order)) {
  719. return '';
  720. }
  721. $array = array();
  722. if (is_string($order) && '[RAND]' != $order) {
  723. $order = array_map('trim', explode(',', $order));
  724. }
  725. if (is_array($order)) {
  726. foreach ($order as $key => $val) {
  727. if (is_numeric($key)) {
  728. list($key, $sort) = explode(' ', strpos($val, ' ') ? $val : $val . ' ');
  729. } else {
  730. $sort = $val;
  731. }
  732. if (preg_match('/^[\w\.]+$/', $key)) {
  733. $sort = strtoupper($sort);
  734. $sort = in_array($sort, array('ASC', 'DESC'), true) ? ' ' . $sort : '';
  735. if (strpos($key, '.')) {
  736. list($alias, $key) = explode('.', $key);
  737. $array[] = $this->parseKey($alias, true) . '.' . $this->parseKey($key, true) . $sort;
  738. } else {
  739. $array[] = $this->parseKey($key, true) . $sort;
  740. }
  741. }
  742. }
  743. } elseif ('[RAND]' == $order) {
  744. // 随机排序
  745. $array[] = $this->parseRand();
  746. }
  747. $order = implode(',', $array);
  748. return !empty($order) ? ' ORDER BY ' . $order : '';
  749. }
  750. /**
  751. * group分析
  752. * @access protected
  753. * @param mixed $group
  754. * @return string
  755. */
  756. protected function parseGroup($group)
  757. {
  758. return !empty($group) ? ' GROUP BY ' . $group : '';
  759. }
  760. /**
  761. * having分析
  762. * @access protected
  763. * @param string $having
  764. * @return string
  765. */
  766. protected function parseHaving($having)
  767. {
  768. return !empty($having) ? ' HAVING ' . $having : '';
  769. }
  770. /**
  771. * comment分析
  772. * @access protected
  773. * @param string $comment
  774. * @return string
  775. */
  776. protected function parseComment($comment)
  777. {
  778. return !empty($comment) ? ' /* ' . $comment . ' */' : '';
  779. }
  780. /**
  781. * distinct分析
  782. * @access protected
  783. * @param mixed $distinct
  784. * @return string
  785. */
  786. protected function parseDistinct($distinct)
  787. {
  788. return !empty($distinct) ? ' DISTINCT ' : '';
  789. }
  790. /**
  791. * union分析
  792. * @access protected
  793. * @param mixed $union
  794. * @return string
  795. */
  796. protected function parseUnion($union)
  797. {
  798. if (empty($union)) {
  799. return '';
  800. }
  801. if (isset($union['_all'])) {
  802. $str = 'UNION ALL ';
  803. unset($union['_all']);
  804. } else {
  805. $str = 'UNION ';
  806. }
  807. foreach ($union as $u) {
  808. $sql[] = $str . (is_array($u) ? $this->buildSelectSql($u) : $u);
  809. }
  810. return implode(' ', $sql);
  811. }
  812. /**
  813. * 参数绑定分析
  814. * @access protected
  815. * @param array $bind
  816. * @return array
  817. */
  818. protected function parseBind($bind)
  819. {
  820. $this->bind = array_merge($this->bind, $bind);
  821. }
  822. /**
  823. * index分析,可在操作链中指定需要强制使用的索引
  824. * @access protected
  825. * @param mixed $index
  826. * @return string
  827. */
  828. protected function parseForce($index)
  829. {
  830. if (empty($index)) {
  831. return '';
  832. }
  833. if (is_array($index)) {
  834. $index = join(",", $index);
  835. }
  836. return sprintf(" FORCE INDEX ( %s ) ", $index);
  837. }
  838. /**
  839. * ON DUPLICATE KEY UPDATE 分析
  840. * @access protected
  841. * @param mixed $duplicate
  842. * @return string
  843. */
  844. protected function parseDuplicate($duplicate)
  845. {
  846. return '';
  847. }
  848. /**
  849. * 插入记录
  850. * @access public
  851. * @param mixed $data 数据
  852. * @param array $options 参数表达式
  853. * @param boolean $replace 是否replace
  854. * @return false | integer
  855. */
  856. public function insert($data, $options = array(), $replace = false)
  857. {
  858. $values = $fields = array();
  859. $this->model = $options['model'];
  860. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  861. foreach ($data as $key => $val) {
  862. if (isset($val[0]) && 'exp' == $val[0]) {
  863. $fields[] = $this->parseKey($key);
  864. $values[] = $val[1];
  865. } elseif (is_null($val)) {
  866. $fields[] = $this->parseKey($key);
  867. $values[] = 'NULL';
  868. } elseif (is_scalar($val)) {
  869. // 过滤非标量数据
  870. $fields[] = $this->parseKey($key);
  871. if (0 === strpos($val, ':') && in_array($val, array_keys($this->bind))) {
  872. $values[] = $val;
  873. } else {
  874. $name = count($this->bind);
  875. $values[] = ':' . $key . '_' . $name;
  876. $this->bindParam($key . '_' . $name, $val);
  877. }
  878. }
  879. }
  880. // 兼容数字传入方式
  881. $replace = (is_numeric($replace) && $replace > 0) ? true : $replace;
  882. $sql = (true === $replace ? 'REPLACE' : 'INSERT') . ' INTO ' . $this->parseTable($options['table']) . ' (' . implode(',', $fields) . ') VALUES (' . implode(',', $values) . ')' . $this->parseDuplicate($replace);
  883. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  884. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  885. }
  886. /**
  887. * 批量插入记录
  888. * @access public
  889. * @param mixed $dataSet 数据集
  890. * @param array $options 参数表达式
  891. * @param boolean $replace 是否replace
  892. * @return false | integer
  893. */
  894. public function insertAll($dataSet, $options = array(), $replace = false)
  895. {
  896. $values = array();
  897. $this->model = $options['model'];
  898. if (!is_array($dataSet[0])) {
  899. return false;
  900. }
  901. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  902. $fields = array_map(array($this, 'parseKey'), array_keys($dataSet[0]));
  903. foreach ($dataSet as $data) {
  904. $value = array();
  905. foreach ($data as $key => $val) {
  906. if (is_array($val) && 'exp' == $val[0]) {
  907. $value[] = $val[1];
  908. } elseif (is_null($val)) {
  909. $value[] = 'NULL';
  910. } elseif (is_scalar($val)) {
  911. if (0 === strpos($val, ':') && in_array($val, array_keys($this->bind))) {
  912. $value[] = $val;
  913. } else {
  914. $name = count($this->bind);
  915. $value[] = ':' . $key . '_' . $name;
  916. $this->bindParam($key . '_' . $name, $val);
  917. }
  918. }
  919. }
  920. $values[] = 'SELECT ' . implode(',', $value);
  921. }
  922. $sql = 'INSERT INTO ' . $this->parseTable($options['table']) . ' (' . implode(',', $fields) . ') ' . implode(' UNION ALL ', $values);
  923. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  924. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  925. }
  926. /**
  927. * 通过Select方式插入记录
  928. * @access public
  929. * @param string $fields 要插入的数据表字段名
  930. * @param string $table 要插入的数据表名
  931. * @param array $option 查询数据参数
  932. * @return false | integer
  933. */
  934. public function selectInsert($fields, $table, $options = array())
  935. {
  936. $this->model = $options['model'];
  937. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  938. if (is_string($fields)) {
  939. $fields = explode(',', $fields);
  940. }
  941. $fields = array_map(array($this, 'parseKey'), $fields);
  942. $sql = 'INSERT INTO ' . $this->parseTable($table) . ' (' . implode(',', $fields) . ') ';
  943. $sql .= $this->buildSelectSql($options);
  944. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  945. }
  946. /**
  947. * 更新记录
  948. * @access public
  949. * @param mixed $data 数据
  950. * @param array $options 表达式
  951. * @return false | integer
  952. */
  953. public function update($data, $options)
  954. {
  955. $this->model = $options['model'];
  956. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  957. $table = $this->parseTable($options['table']);
  958. $sql = 'UPDATE ' . $table . $this->parseSet($data);
  959. if (strpos($table, ',')) {
  960. // 多表更新支持JOIN操作
  961. $sql .= $this->parseJoin(!empty($options['join']) ? $options['join'] : '');
  962. }
  963. $sql .= $this->parseWhere(!empty($options['where']) ? $options['where'] : '');
  964. if (!strpos($table, ',')) {
  965. // 单表更新支持order和lmit
  966. $sql .= $this->parseOrder(!empty($options['order']) ? $options['order'] : '')
  967. . $this->parseLimit(!empty($options['limit']) ? $options['limit'] : '');
  968. }
  969. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  970. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  971. }
  972. /**
  973. * 删除记录
  974. * @access public
  975. * @param array $options 表达式
  976. * @return false | integer
  977. */
  978. public function delete($options = array())
  979. {
  980. $this->model = $options['model'];
  981. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  982. $table = $this->parseTable($options['table']);
  983. $sql = 'DELETE FROM ' . $table;
  984. if (strpos($table, ',')) {
  985. // 多表删除支持USING和JOIN操作
  986. if (!empty($options['using'])) {
  987. $sql .= ' USING ' . $this->parseTable($options['using']) . ' ';
  988. }
  989. $sql .= $this->parseJoin(!empty($options['join']) ? $options['join'] : '');
  990. }
  991. $sql .= $this->parseWhere(!empty($options['where']) ? $options['where'] : '');
  992. if (!strpos($table, ',')) {
  993. // 单表删除支持order和limit
  994. $sql .= $this->parseOrder(!empty($options['order']) ? $options['order'] : '')
  995. . $this->parseLimit(!empty($options['limit']) ? $options['limit'] : '');
  996. }
  997. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  998. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  999. }
  1000. /**
  1001. * 查找记录
  1002. * @access public
  1003. * @param array $options 表达式
  1004. * @return mixed
  1005. */
  1006. public function select($options = array())
  1007. {
  1008. $this->model = $options['model'];
  1009. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  1010. $sql = $this->buildSelectSql($options);
  1011. $result = $this->query($sql, !empty($options['fetch_sql']) ? true : false, !empty($options['master']) ? true : false);
  1012. return $result;
  1013. }
  1014. /**
  1015. * 生成查询SQL
  1016. * @access public
  1017. * @param array $options 表达式
  1018. * @return string
  1019. */
  1020. public function buildSelectSql($options = array())
  1021. {
  1022. if (isset($options['page'])) {
  1023. // 根据页数计算limit
  1024. list($page, $listRows) = $options['page'];
  1025. $page = $page > 0 ? $page : 1;
  1026. $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
  1027. $offset = $listRows * ($page - 1);
  1028. $options['limit'] = $offset . ',' . $listRows;
  1029. }
  1030. $sql = $this->parseSql($this->selectSql, $options);
  1031. return $sql;
  1032. }
  1033. /**
  1034. * 替换SQL语句中表达式
  1035. * @access public
  1036. * @param array $options 表达式
  1037. * @return string
  1038. */
  1039. public function parseSql($sql, $options = array())
  1040. {
  1041. $sql = str_replace(
  1042. array('%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'),
  1043. array(
  1044. $this->parseTable($options['table']),
  1045. $this->parseDistinct(isset($options['distinct']) ? $options['distinct'] : false),
  1046. $this->parseField(!empty($options['field']) ? $options['field'] : '*'),
  1047. $this->parseJoin(!empty($options['join']) ? $options['join'] : ''),
  1048. $this->parseWhere(!empty($options['where']) ? $options['where'] : ''),
  1049. $this->parseGroup(!empty($options['group']) ? $options['group'] : ''),
  1050. $this->parseHaving(!empty($options['having']) ? $options['having'] : ''),
  1051. $this->parseOrder(!empty($options['order']) ? $options['order'] : ''),
  1052. $this->parseLimit(!empty($options['limit']) ? $options['limit'] : ''),
  1053. $this->parseUnion(!empty($options['union']) ? $options['union'] : ''),
  1054. $this->parseLock(isset($options['lock']) ? $options['lock'] : false),
  1055. $this->parseComment(!empty($options['comment']) ? $options['comment'] : ''),
  1056. $this->parseForce(!empty($options['force']) ? $options['force'] : ''),
  1057. ), $sql);
  1058. return $sql;
  1059. }
  1060. /**
  1061. * 获取最近一次查询的sql语句
  1062. * @param string $model 模型名
  1063. * @access public
  1064. * @return string
  1065. */
  1066. public function getLastSql($model = '')
  1067. {
  1068. return $model ? $this->modelSql[$model] : $this->queryStr;
  1069. }
  1070. /**
  1071. * 获取最近插入的ID
  1072. * @access public
  1073. * @return string
  1074. */
  1075. public function getLastInsID()
  1076. {
  1077. return $this->lastInsID;
  1078. }
  1079. /**
  1080. * 获取最近的错误信息
  1081. * @access public
  1082. * @return string
  1083. */
  1084. public function getError()
  1085. {
  1086. return $this->error;
  1087. }
  1088. /**
  1089. * SQL指令安全过滤
  1090. * @access public
  1091. * @param string $str SQL字符串
  1092. * @return string
  1093. */
  1094. public function escapeString($str)
  1095. {
  1096. return addslashes($str);
  1097. }
  1098. /**
  1099. * 设置当前操作模型
  1100. * @access public
  1101. * @param string $model 模型名
  1102. * @return void
  1103. */
  1104. public function setModel($model)
  1105. {
  1106. $this->model = $model;
  1107. }
  1108. /**
  1109. * 数据库调试 记录当前SQL
  1110. * @access protected
  1111. * @param boolean $start 调试开始标记 true 开始 false 结束
  1112. */
  1113. protected function debug($start)
  1114. {
  1115. if ($this->config['debug']) {
  1116. // 开启数据库调试模式
  1117. if ($start) {
  1118. G('queryStartTime');
  1119. } else {
  1120. $this->modelSql[$this->model] = $this->queryStr;
  1121. //$this->model = '_think_';
  1122. // 记录操作结束时间
  1123. G('queryEndTime');
  1124. trace($this->queryStr . ' [ RunTime:' . G('queryStartTime', 'queryEndTime') . 's ]', '', 'SQL');
  1125. }
  1126. }
  1127. }
  1128. /**
  1129. * 初始化数据库连接
  1130. * @access protected
  1131. * @param boolean $master 主服务器
  1132. * @return void
  1133. */
  1134. protected function initConnect($master = true)
  1135. {
  1136. // 开启事物时用同一个连接进行操作
  1137. if ($this->transPDO) {
  1138. return $this->transPDO;
  1139. }
  1140. if (!empty($this->config['deploy']))
  1141. // 采用分布式数据库
  1142. {
  1143. $this->_linkID = $this->multiConnect($master);
  1144. } else
  1145. // 默认单数据库
  1146. if (!$this->_linkID) {
  1147. $this->_linkID = $this->connect();
  1148. }
  1149. }
  1150. /**
  1151. * 连接分布式服务器
  1152. * @access protected
  1153. * @param boolean $master 主服务器
  1154. * @return void
  1155. */
  1156. protected function multiConnect($master = false)
  1157. {
  1158. // 分布式数据库配置解析
  1159. $_config['username'] = explode(',', $this->config['username']);
  1160. $_config['password'] = explode(',', $this->config['password']);
  1161. $_config['hostname'] = explode(',', $this->config['hostname']);
  1162. $_config['hostport'] = explode(',', $this->config['hostport']);
  1163. $_config['database'] = explode(',', $this->config['database']);
  1164. $_config['dsn'] = explode(',', $this->config['dsn']);
  1165. $_config['charset'] = explode(',', $this->config['charset']);
  1166. $m = floor(mt_rand(0, $this->config['master_num'] - 1));
  1167. // 数据库读写是否分离
  1168. if ($this->config['rw_separate']) {
  1169. // 主从式采用读写分离
  1170. if ($master)
  1171. // 主服务器写入
  1172. {
  1173. $r = $m;
  1174. } else {
  1175. if (is_numeric($this->config['slave_no'])) {
  1176. // 指定服务器读
  1177. $r = $this->config['slave_no'];
  1178. } else {
  1179. // 读操作连接从服务器
  1180. $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1)); // 每次随机连接的数据库
  1181. }
  1182. }
  1183. } else {
  1184. // 读写操作不区分服务器
  1185. $r = floor(mt_rand(0, count($_config['hostname']) - 1)); // 每次随机连接的数据库
  1186. }
  1187. if ($m != $r) {
  1188. $db_master = array(
  1189. 'username' => isset($_config['username'][$m]) ? $_config['username'][$m] : $_config['username'][0],
  1190. 'password' => isset($_config['password'][$m]) ? $_config['password'][$m] : $_config['password'][0],
  1191. 'hostname' => isset($_config['hostname'][$m]) ? $_config['hostname'][$m] : $_config['hostname'][0],
  1192. 'hostport' => isset($_config['hostport'][$m]) ? $_config['hostport'][$m] : $_config['hostport'][0],
  1193. 'database' => isset($_config['database'][$m]) ? $_config['database'][$m] : $_config['database'][0],
  1194. 'dsn' => isset($_config['dsn'][$m]) ? $_config['dsn'][$m] : $_config['dsn'][0],
  1195. 'charset' => isset($_config['charset'][$m]) ? $_config['charset'][$m] : $_config['charset'][0],
  1196. );
  1197. }
  1198. $db_config = array(
  1199. 'username' => isset($_config['username'][$r]) ? $_config['username'][$r] : $_config['username'][0],
  1200. 'password' => isset($_config['password'][$r]) ? $_config['password'][$r] : $_config['password'][0],
  1201. 'hostname' => isset($_config['hostname'][$r]) ? $_config['hostname'][$r] : $_config['hostname'][0],
  1202. 'hostport' => isset($_config['hostport'][$r]) ? $_config['hostport'][$r] : $_config['hostport'][0],
  1203. 'database' => isset($_config['database'][$r]) ? $_config['database'][$r] : $_config['database'][0],
  1204. 'dsn' => isset($_config['dsn'][$r]) ? $_config['dsn'][$r] : $_config['dsn'][0],
  1205. 'charset' => isset($_config['charset'][$r]) ? $_config['charset'][$r] : $_config['charset'][0],
  1206. );
  1207. return $this->connect($db_config, $r, $r == $m ? false : $db_master);
  1208. }
  1209. /**
  1210. * 析构方法
  1211. * @access public
  1212. */
  1213. public function __destruct()
  1214. {
  1215. // 释放查询
  1216. if ($this->PDOStatement) {
  1217. $this->free();
  1218. }
  1219. // 关闭连接
  1220. $this->close();
  1221. }
  1222. }