Driver.class.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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 ($this->transTimes == 1) {
  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 if ($this->transTimes > 0) {
  289. $this->transTimes--;
  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 protected
  425. * @param string $key
  426. * @return string
  427. */
  428. protected function parseKey($key)
  429. {
  430. return $key;
  431. }
  432. /**
  433. * value分析
  434. * @access protected
  435. * @param mixed $value
  436. * @return string
  437. */
  438. protected function parseValue($value)
  439. {
  440. if (is_string($value)) {
  441. $value = strpos($value, ':') === 0 && in_array($value, array_keys($this->bind)) ? $this->escapeString($value) : '\'' . $this->escapeString($value) . '\'';
  442. } elseif (isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp') {
  443. $value = $this->escapeString($value[1]);
  444. } elseif (is_array($value)) {
  445. $value = array_map(array($this, 'parseValue'), $value);
  446. } elseif (is_bool($value)) {
  447. $value = $value ? '1' : '0';
  448. } elseif (is_null($value)) {
  449. $value = 'null';
  450. }
  451. return $value;
  452. }
  453. /**
  454. * field分析
  455. * @access protected
  456. * @param mixed $fields
  457. * @return string
  458. */
  459. protected function parseField($fields)
  460. {
  461. if (is_string($fields) && '' !== $fields) {
  462. $fields = explode(',', $fields);
  463. }
  464. if (is_array($fields)) {
  465. // 完善数组方式传字段名的支持
  466. // 支持 'field1'=>'field2' 这样的字段别名定义
  467. $array = array();
  468. foreach ($fields as $key => $field) {
  469. if (!is_numeric($key)) {
  470. $array[] = $this->parseKey($key) . ' AS ' . $this->parseKey($field);
  471. } else {
  472. $array[] = $this->parseKey($field);
  473. }
  474. }
  475. $fieldsStr = implode(',', $array);
  476. } else {
  477. $fieldsStr = '*';
  478. }
  479. //TODO 如果是查询全部字段,并且是join的方式,那么就把要查的表加个别名,以免字段被覆盖
  480. return $fieldsStr;
  481. }
  482. /**
  483. * table分析
  484. * @access protected
  485. * @param mixed $table
  486. * @return string
  487. */
  488. protected function parseTable($tables)
  489. {
  490. if (is_array($tables)) {
  491. // 支持别名定义
  492. $array = array();
  493. foreach ($tables as $table => $alias) {
  494. if (!is_numeric($table)) {
  495. $array[] = $this->parseKey($table) . ' ' . $this->parseKey($alias);
  496. } else {
  497. $array[] = $this->parseKey($alias);
  498. }
  499. }
  500. $tables = $array;
  501. } elseif (is_string($tables)) {
  502. $tables = array_map(array($this, 'parseKey'), explode(',', $tables));
  503. }
  504. return implode(',', $tables);
  505. }
  506. /**
  507. * where分析
  508. * @access protected
  509. * @param mixed $where
  510. * @return string
  511. */
  512. protected function parseWhere($where)
  513. {
  514. $whereStr = '';
  515. if (is_string($where)) {
  516. // 直接使用字符串条件
  517. $whereStr = $where;
  518. } else {
  519. // 使用数组表达式
  520. $operate = isset($where['_logic']) ? strtoupper($where['_logic']) : '';
  521. if (in_array($operate, array('AND', 'OR', 'XOR'))) {
  522. // 定义逻辑运算规则 例如 OR XOR AND NOT
  523. $operate = ' ' . $operate . ' ';
  524. unset($where['_logic']);
  525. } else {
  526. // 默认进行 AND 运算
  527. $operate = ' AND ';
  528. }
  529. foreach ($where as $key => $val) {
  530. if (is_numeric($key)) {
  531. $key = '_complex';
  532. }
  533. if (0 === strpos($key, '_')) {
  534. // 解析特殊条件表达式
  535. $whereStr .= $this->parseThinkWhere($key, $val);
  536. } else {
  537. // 查询字段的安全过滤
  538. // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
  539. // E(L('_EXPRESS_ERROR_').':'.$key);
  540. // }
  541. // 多条件支持
  542. $multi = is_array($val) && isset($val['_multi']);
  543. $key = trim($key);
  544. if (strpos($key, '|')) {
  545. // 支持 name|title|nickname 方式定义查询字段
  546. $array = explode('|', $key);
  547. $str = array();
  548. foreach ($array as $m => $k) {
  549. $v = $multi ? $val[$m] : $val;
  550. $str[] = $this->parseWhereItem($this->parseKey($k), $v);
  551. }
  552. $whereStr .= '( ' . implode(' OR ', $str) . ' )';
  553. } elseif (strpos($key, '&')) {
  554. $array = explode('&', $key);
  555. $str = array();
  556. foreach ($array as $m => $k) {
  557. $v = $multi ? $val[$m] : $val;
  558. $str[] = '(' . $this->parseWhereItem($this->parseKey($k), $v) . ')';
  559. }
  560. $whereStr .= '( ' . implode(' AND ', $str) . ' )';
  561. } else {
  562. $whereStr .= $this->parseWhereItem($this->parseKey($key), $val);
  563. }
  564. }
  565. $whereStr .= $operate;
  566. }
  567. $whereStr = substr($whereStr, 0, -strlen($operate));
  568. }
  569. return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
  570. }
  571. // where子单元分析
  572. protected function parseWhereItem($key, $val)
  573. {
  574. $whereStr = '';
  575. if (is_array($val)) {
  576. if (is_string($val[0])) {
  577. $exp = strtolower($val[0]);
  578. if (preg_match('/^(eq|neq|gt|egt|lt|elt)$/', $exp)) {
  579. // 比较运算
  580. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($val[1]);
  581. } elseif (preg_match('/^(notlike|like)$/', $exp)) {
  582. // 模糊查找
  583. if (is_array($val[1])) {
  584. $likeLogic = isset($val[2]) ? strtoupper($val[2]) : 'OR';
  585. if (in_array($likeLogic, array('AND', 'OR', 'XOR'))) {
  586. $like = array();
  587. foreach ($val[1] as $item) {
  588. $like[] = $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($item);
  589. }
  590. $whereStr .= '(' . implode(' ' . $likeLogic . ' ', $like) . ')';
  591. }
  592. } else {
  593. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($val[1]);
  594. }
  595. } elseif ('bind' == $exp) {
  596. // 使用表达式
  597. $whereStr .= $key . ' = :' . $val[1];
  598. } elseif ('exp' == $exp) {
  599. // 使用表达式
  600. $whereStr .= $key . ' ' . $val[1];
  601. } elseif (preg_match('/^(notin|not in|in)$/', $exp)) {
  602. // IN 运算
  603. if (isset($val[2]) && 'exp' == $val[2]) {
  604. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $val[1];
  605. } else {
  606. if (is_string($val[1])) {
  607. $val[1] = explode(',', $val[1]);
  608. }
  609. $zone = implode(',', $this->parseValue($val[1]));
  610. $whereStr .= $key . ' ' . $this->exp[$exp] . ' (' . $zone . ')';
  611. }
  612. } elseif (preg_match('/^(notbetween|not between|between)$/', $exp)) {
  613. // BETWEEN运算
  614. $data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
  615. $whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($data[0]) . ' AND ' . $this->parseValue($data[1]);
  616. } else {
  617. E(L('_EXPRESS_ERROR_') . ':' . $val[0]);
  618. }
  619. } else {
  620. $count = count($val);
  621. $rule = isset($val[$count - 1]) ? (is_array($val[$count - 1]) ? strtoupper($val[$count - 1][0]) : strtoupper($val[$count - 1])) : '';
  622. if (in_array($rule, array('AND', 'OR', 'XOR'))) {
  623. $count = $count - 1;
  624. } else {
  625. $rule = 'AND';
  626. }
  627. for ($i = 0; $i < $count; $i++) {
  628. $data = is_array($val[$i]) ? $val[$i][1] : $val[$i];
  629. if ('exp' == strtolower($val[$i][0])) {
  630. $whereStr .= $key . ' ' . $data . ' ' . $rule . ' ';
  631. } else {
  632. $whereStr .= $this->parseWhereItem($key, $val[$i]) . ' ' . $rule . ' ';
  633. }
  634. }
  635. $whereStr = '( ' . substr($whereStr, 0, -4) . ' )';
  636. }
  637. } else {
  638. //对字符串类型字段采用模糊匹配
  639. $likeFields = $this->config['db_like_fields'];
  640. if ($likeFields && preg_match('/^(' . $likeFields . ')$/i', $key)) {
  641. $whereStr .= $key . ' LIKE ' . $this->parseValue('%' . $val . '%');
  642. } else {
  643. $whereStr .= $key . ' = ' . $this->parseValue($val);
  644. }
  645. }
  646. return $whereStr;
  647. }
  648. /**
  649. * 特殊条件分析
  650. * @access protected
  651. * @param string $key
  652. * @param mixed $val
  653. * @return string
  654. */
  655. protected function parseThinkWhere($key, $val)
  656. {
  657. $whereStr = '';
  658. switch ($key) {
  659. case '_string':
  660. // 字符串模式查询条件
  661. $whereStr = $val;
  662. break;
  663. case '_complex':
  664. // 复合查询条件
  665. $whereStr = substr($this->parseWhere($val), 6);
  666. break;
  667. case '_query':
  668. // 字符串模式查询条件
  669. parse_str($val, $where);
  670. if (isset($where['_logic'])) {
  671. $op = ' ' . strtoupper($where['_logic']) . ' ';
  672. unset($where['_logic']);
  673. } else {
  674. $op = ' AND ';
  675. }
  676. $array = array();
  677. foreach ($where as $field => $data) {
  678. $array[] = $this->parseKey($field) . ' = ' . $this->parseValue($data);
  679. }
  680. $whereStr = implode($op, $array);
  681. break;
  682. }
  683. return '( ' . $whereStr . ' )';
  684. }
  685. /**
  686. * limit分析
  687. * @access protected
  688. * @param mixed $lmit
  689. * @return string
  690. */
  691. protected function parseLimit($limit)
  692. {
  693. return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
  694. }
  695. /**
  696. * join分析
  697. * @access protected
  698. * @param mixed $join
  699. * @return string
  700. */
  701. protected function parseJoin($join)
  702. {
  703. $joinStr = '';
  704. if (!empty($join)) {
  705. $joinStr = ' ' . implode(' ', $join) . ' ';
  706. }
  707. return $joinStr;
  708. }
  709. /**
  710. * order分析
  711. * @access protected
  712. * @param mixed $order
  713. * @return string
  714. */
  715. protected function parseOrder($order)
  716. {
  717. if (empty($order)) {
  718. return '';
  719. }
  720. $array = array();
  721. if (is_array($order)) {
  722. foreach ($order as $key => $val) {
  723. if (is_numeric($key)) {
  724. if (false === strpos($val, '(')) {
  725. $array[] = $this->parseKey($val);
  726. }
  727. } else {
  728. $sort = in_array(strtolower($val), array('asc', 'desc')) ? ' ' . $val : '';
  729. $array[] = $this->parseKey($key) . $sort;
  730. }
  731. }
  732. } elseif ('[RAND]' == $order) {
  733. // 随机排序
  734. $array[] = $this->parseRand();
  735. } else {
  736. foreach (explode(',', $order) as $val) {
  737. if (preg_match('/\s+(ASC|DESC)$/i', rtrim($val), $match, PREG_OFFSET_CAPTURE)) {
  738. $array[] = $this->parseKey(ltrim(substr($val, 0, $match[0][1]))) . ' ' . $match[1][0];
  739. } elseif (false === strpos($val, '(')) {
  740. $array[] = $this->parseKey($val);
  741. }
  742. }
  743. }
  744. $order = implode(',', $array);
  745. return !empty($order) ? ' ORDER BY ' . $order : '';
  746. }
  747. /**
  748. * group分析
  749. * @access protected
  750. * @param mixed $group
  751. * @return string
  752. */
  753. protected function parseGroup($group)
  754. {
  755. return !empty($group) ? ' GROUP BY ' . $group : '';
  756. }
  757. /**
  758. * having分析
  759. * @access protected
  760. * @param string $having
  761. * @return string
  762. */
  763. protected function parseHaving($having)
  764. {
  765. return !empty($having) ? ' HAVING ' . $having : '';
  766. }
  767. /**
  768. * comment分析
  769. * @access protected
  770. * @param string $comment
  771. * @return string
  772. */
  773. protected function parseComment($comment)
  774. {
  775. return !empty($comment) ? ' /* ' . $comment . ' */' : '';
  776. }
  777. /**
  778. * distinct分析
  779. * @access protected
  780. * @param mixed $distinct
  781. * @return string
  782. */
  783. protected function parseDistinct($distinct)
  784. {
  785. return !empty($distinct) ? ' DISTINCT ' : '';
  786. }
  787. /**
  788. * union分析
  789. * @access protected
  790. * @param mixed $union
  791. * @return string
  792. */
  793. protected function parseUnion($union)
  794. {
  795. if (empty($union)) {
  796. return '';
  797. }
  798. if (isset($union['_all'])) {
  799. $str = 'UNION ALL ';
  800. unset($union['_all']);
  801. } else {
  802. $str = 'UNION ';
  803. }
  804. foreach ($union as $u) {
  805. $sql[] = $str . (is_array($u) ? $this->buildSelectSql($u) : $u);
  806. }
  807. return implode(' ', $sql);
  808. }
  809. /**
  810. * 参数绑定分析
  811. * @access protected
  812. * @param array $bind
  813. * @return array
  814. */
  815. protected function parseBind($bind)
  816. {
  817. $this->bind = array_merge($this->bind, $bind);
  818. }
  819. /**
  820. * index分析,可在操作链中指定需要强制使用的索引
  821. * @access protected
  822. * @param mixed $index
  823. * @return string
  824. */
  825. protected function parseForce($index)
  826. {
  827. if (empty($index)) {
  828. return '';
  829. }
  830. if (is_array($index)) {
  831. $index = join(",", $index);
  832. }
  833. return sprintf(" FORCE INDEX ( %s ) ", $index);
  834. }
  835. /**
  836. * ON DUPLICATE KEY UPDATE 分析
  837. * @access protected
  838. * @param mixed $duplicate
  839. * @return string
  840. */
  841. protected function parseDuplicate($duplicate)
  842. {
  843. return '';
  844. }
  845. /**
  846. * 插入记录
  847. * @access public
  848. * @param mixed $data 数据
  849. * @param array $options 参数表达式
  850. * @param boolean $replace 是否replace
  851. * @return false | integer
  852. */
  853. public function insert($data, $options = array(), $replace = false)
  854. {
  855. $values = $fields = array();
  856. $this->model = $options['model'];
  857. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  858. foreach ($data as $key => $val) {
  859. if (isset($val[0]) && 'exp' == $val[0]) {
  860. $fields[] = $this->parseKey($key);
  861. $values[] = $val[1];
  862. } elseif (is_null($val)) {
  863. $fields[] = $this->parseKey($key);
  864. $values[] = 'NULL';
  865. } elseif (is_scalar($val)) {
  866. // 过滤非标量数据
  867. $fields[] = $this->parseKey($key);
  868. if (0 === strpos($val, ':') && in_array($val, array_keys($this->bind))) {
  869. $values[] = $val;
  870. } else {
  871. $name = count($this->bind);
  872. $values[] = ':' . $key . '_' . $name;
  873. $this->bindParam($key . '_' . $name, $val);
  874. }
  875. }
  876. }
  877. // 兼容数字传入方式
  878. $replace = (is_numeric($replace) && $replace > 0) ? true : $replace;
  879. $sql = (true === $replace ? 'REPLACE' : 'INSERT') . ' INTO ' . $this->parseTable($options['table']) . ' (' . implode(',', $fields) . ') VALUES (' . implode(',', $values) . ')' . $this->parseDuplicate($replace);
  880. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  881. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  882. }
  883. /**
  884. * 批量插入记录
  885. * @access public
  886. * @param mixed $dataSet 数据集
  887. * @param array $options 参数表达式
  888. * @param boolean $replace 是否replace
  889. * @return false | integer
  890. */
  891. public function insertAll($dataSet, $options = array(), $replace = false)
  892. {
  893. $values = array();
  894. $this->model = $options['model'];
  895. if (!is_array($dataSet[0])) {
  896. return false;
  897. }
  898. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  899. $fields = array_map(array($this, 'parseKey'), array_keys($dataSet[0]));
  900. foreach ($dataSet as $data) {
  901. $value = array();
  902. foreach ($data as $key => $val) {
  903. if (is_array($val) && 'exp' == $val[0]) {
  904. $value[] = $val[1];
  905. } elseif (is_null($val)) {
  906. $value[] = 'NULL';
  907. } elseif (is_scalar($val)) {
  908. if (0 === strpos($val, ':') && in_array($val, array_keys($this->bind))) {
  909. $value[] = $val;
  910. } else {
  911. $name = count($this->bind);
  912. $value[] = ':' . $key . '_' . $name;
  913. $this->bindParam($key . '_' . $name, $val);
  914. }
  915. }
  916. }
  917. $values[] = 'SELECT ' . implode(',', $value);
  918. }
  919. $sql = 'INSERT INTO ' . $this->parseTable($options['table']) . ' (' . implode(',', $fields) . ') ' . implode(' UNION ALL ', $values);
  920. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  921. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  922. }
  923. /**
  924. * 通过Select方式插入记录
  925. * @access public
  926. * @param string $fields 要插入的数据表字段名
  927. * @param string $table 要插入的数据表名
  928. * @param array $option 查询数据参数
  929. * @return false | integer
  930. */
  931. public function selectInsert($fields, $table, $options = array())
  932. {
  933. $this->model = $options['model'];
  934. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  935. if (is_string($fields)) {
  936. $fields = explode(',', $fields);
  937. }
  938. $fields = array_map(array($this, 'parseKey'), $fields);
  939. $sql = 'INSERT INTO ' . $this->parseTable($table) . ' (' . implode(',', $fields) . ') ';
  940. $sql .= $this->buildSelectSql($options);
  941. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  942. }
  943. /**
  944. * 更新记录
  945. * @access public
  946. * @param mixed $data 数据
  947. * @param array $options 表达式
  948. * @return false | integer
  949. */
  950. public function update($data, $options)
  951. {
  952. $this->model = $options['model'];
  953. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  954. $table = $this->parseTable($options['table']);
  955. $sql = 'UPDATE ' . $table . $this->parseSet($data);
  956. if (strpos($table, ',')) {
  957. // 多表更新支持JOIN操作
  958. $sql .= $this->parseJoin(!empty($options['join']) ? $options['join'] : '');
  959. }
  960. $sql .= $this->parseWhere(!empty($options['where']) ? $options['where'] : '');
  961. if (!strpos($table, ',')) {
  962. // 单表更新支持order和lmit
  963. $sql .= $this->parseOrder(!empty($options['order']) ? $options['order'] : '')
  964. . $this->parseLimit(!empty($options['limit']) ? $options['limit'] : '');
  965. }
  966. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  967. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  968. }
  969. /**
  970. * 删除记录
  971. * @access public
  972. * @param array $options 表达式
  973. * @return false | integer
  974. */
  975. public function delete($options = array())
  976. {
  977. $this->model = $options['model'];
  978. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  979. $table = $this->parseTable($options['table']);
  980. $sql = 'DELETE FROM ' . $table;
  981. if (strpos($table, ',')) {
  982. // 多表删除支持USING和JOIN操作
  983. if (!empty($options['using'])) {
  984. $sql .= ' USING ' . $this->parseTable($options['using']) . ' ';
  985. }
  986. $sql .= $this->parseJoin(!empty($options['join']) ? $options['join'] : '');
  987. }
  988. $sql .= $this->parseWhere(!empty($options['where']) ? $options['where'] : '');
  989. if (!strpos($table, ',')) {
  990. // 单表删除支持order和limit
  991. $sql .= $this->parseOrder(!empty($options['order']) ? $options['order'] : '')
  992. . $this->parseLimit(!empty($options['limit']) ? $options['limit'] : '');
  993. }
  994. $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : '');
  995. return $this->execute($sql, !empty($options['fetch_sql']) ? true : false);
  996. }
  997. /**
  998. * 查找记录
  999. * @access public
  1000. * @param array $options 表达式
  1001. * @return mixed
  1002. */
  1003. public function select($options = array())
  1004. {
  1005. $this->model = $options['model'];
  1006. $this->parseBind(!empty($options['bind']) ? $options['bind'] : array());
  1007. $sql = $this->buildSelectSql($options);
  1008. $result = $this->query($sql, !empty($options['fetch_sql']) ? true : false, !empty($options['master']) ? true : false);
  1009. return $result;
  1010. }
  1011. /**
  1012. * 生成查询SQL
  1013. * @access public
  1014. * @param array $options 表达式
  1015. * @return string
  1016. */
  1017. public function buildSelectSql($options = array())
  1018. {
  1019. if (isset($options['page'])) {
  1020. // 根据页数计算limit
  1021. list($page, $listRows) = $options['page'];
  1022. $page = $page > 0 ? $page : 1;
  1023. $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20);
  1024. $offset = $listRows * ($page - 1);
  1025. $options['limit'] = $offset . ',' . $listRows;
  1026. }
  1027. $sql = $this->parseSql($this->selectSql, $options);
  1028. return $sql;
  1029. }
  1030. /**
  1031. * 替换SQL语句中表达式
  1032. * @access public
  1033. * @param array $options 表达式
  1034. * @return string
  1035. */
  1036. public function parseSql($sql, $options = array())
  1037. {
  1038. $sql = str_replace(
  1039. array('%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'),
  1040. array(
  1041. $this->parseTable($options['table']),
  1042. $this->parseDistinct(isset($options['distinct']) ? $options['distinct'] : false),
  1043. $this->parseField(!empty($options['field']) ? $options['field'] : '*'),
  1044. $this->parseJoin(!empty($options['join']) ? $options['join'] : ''),
  1045. $this->parseWhere(!empty($options['where']) ? $options['where'] : ''),
  1046. $this->parseGroup(!empty($options['group']) ? $options['group'] : ''),
  1047. $this->parseHaving(!empty($options['having']) ? $options['having'] : ''),
  1048. $this->parseOrder(!empty($options['order']) ? $options['order'] : ''),
  1049. $this->parseLimit(!empty($options['limit']) ? $options['limit'] : ''),
  1050. $this->parseUnion(!empty($options['union']) ? $options['union'] : ''),
  1051. $this->parseLock(isset($options['lock']) ? $options['lock'] : false),
  1052. $this->parseComment(!empty($options['comment']) ? $options['comment'] : ''),
  1053. $this->parseForce(!empty($options['force']) ? $options['force'] : ''),
  1054. ), $sql);
  1055. return $sql;
  1056. }
  1057. /**
  1058. * 获取最近一次查询的sql语句
  1059. * @param string $model 模型名
  1060. * @access public
  1061. * @return string
  1062. */
  1063. public function getLastSql($model = '')
  1064. {
  1065. return $model ? $this->modelSql[$model] : $this->queryStr;
  1066. }
  1067. /**
  1068. * 获取最近插入的ID
  1069. * @access public
  1070. * @return string
  1071. */
  1072. public function getLastInsID()
  1073. {
  1074. return $this->lastInsID;
  1075. }
  1076. /**
  1077. * 获取最近的错误信息
  1078. * @access public
  1079. * @return string
  1080. */
  1081. public function getError()
  1082. {
  1083. return $this->error;
  1084. }
  1085. /**
  1086. * SQL指令安全过滤
  1087. * @access public
  1088. * @param string $str SQL字符串
  1089. * @return string
  1090. */
  1091. public function escapeString($str)
  1092. {
  1093. return addslashes($str);
  1094. }
  1095. /**
  1096. * 设置当前操作模型
  1097. * @access public
  1098. * @param string $model 模型名
  1099. * @return void
  1100. */
  1101. public function setModel($model)
  1102. {
  1103. $this->model = $model;
  1104. }
  1105. /**
  1106. * 数据库调试 记录当前SQL
  1107. * @access protected
  1108. * @param boolean $start 调试开始标记 true 开始 false 结束
  1109. */
  1110. protected function debug($start)
  1111. {
  1112. if ($this->config['debug']) {
  1113. // 开启数据库调试模式
  1114. if ($start) {
  1115. G('queryStartTime');
  1116. } else {
  1117. $this->modelSql[$this->model] = $this->queryStr;
  1118. //$this->model = '_think_';
  1119. // 记录操作结束时间
  1120. G('queryEndTime');
  1121. trace($this->queryStr . ' [ RunTime:' . G('queryStartTime', 'queryEndTime') . 's ]', '', 'SQL');
  1122. }
  1123. }
  1124. }
  1125. /**
  1126. * 初始化数据库连接
  1127. * @access protected
  1128. * @param boolean $master 主服务器
  1129. * @return void
  1130. */
  1131. protected function initConnect($master = true)
  1132. {
  1133. // 开启事物时用同一个连接进行操作
  1134. if ($this->transPDO) {
  1135. return $this->transPDO;
  1136. }
  1137. if (!empty($this->config['deploy']))
  1138. // 采用分布式数据库
  1139. {
  1140. $this->_linkID = $this->multiConnect($master);
  1141. } else
  1142. // 默认单数据库
  1143. if (!$this->_linkID) {
  1144. $this->_linkID = $this->connect();
  1145. }
  1146. }
  1147. /**
  1148. * 连接分布式服务器
  1149. * @access protected
  1150. * @param boolean $master 主服务器
  1151. * @return void
  1152. */
  1153. protected function multiConnect($master = false)
  1154. {
  1155. // 分布式数据库配置解析
  1156. $_config['username'] = explode(',', $this->config['username']);
  1157. $_config['password'] = explode(',', $this->config['password']);
  1158. $_config['hostname'] = explode(',', $this->config['hostname']);
  1159. $_config['hostport'] = explode(',', $this->config['hostport']);
  1160. $_config['database'] = explode(',', $this->config['database']);
  1161. $_config['dsn'] = explode(',', $this->config['dsn']);
  1162. $_config['charset'] = explode(',', $this->config['charset']);
  1163. $m = floor(mt_rand(0, $this->config['master_num'] - 1));
  1164. // 数据库读写是否分离
  1165. if ($this->config['rw_separate']) {
  1166. // 主从式采用读写分离
  1167. if ($master)
  1168. // 主服务器写入
  1169. {
  1170. $r = $m;
  1171. } else {
  1172. if (is_numeric($this->config['slave_no'])) {
  1173. // 指定服务器读
  1174. $r = $this->config['slave_no'];
  1175. } else {
  1176. // 读操作连接从服务器
  1177. $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1)); // 每次随机连接的数据库
  1178. }
  1179. }
  1180. } else {
  1181. // 读写操作不区分服务器
  1182. $r = floor(mt_rand(0, count($_config['hostname']) - 1)); // 每次随机连接的数据库
  1183. }
  1184. if ($m != $r) {
  1185. $db_master = array(
  1186. 'username' => isset($_config['username'][$m]) ? $_config['username'][$m] : $_config['username'][0],
  1187. 'password' => isset($_config['password'][$m]) ? $_config['password'][$m] : $_config['password'][0],
  1188. 'hostname' => isset($_config['hostname'][$m]) ? $_config['hostname'][$m] : $_config['hostname'][0],
  1189. 'hostport' => isset($_config['hostport'][$m]) ? $_config['hostport'][$m] : $_config['hostport'][0],
  1190. 'database' => isset($_config['database'][$m]) ? $_config['database'][$m] : $_config['database'][0],
  1191. 'dsn' => isset($_config['dsn'][$m]) ? $_config['dsn'][$m] : $_config['dsn'][0],
  1192. 'charset' => isset($_config['charset'][$m]) ? $_config['charset'][$m] : $_config['charset'][0],
  1193. );
  1194. }
  1195. $db_config = array(
  1196. 'username' => isset($_config['username'][$r]) ? $_config['username'][$r] : $_config['username'][0],
  1197. 'password' => isset($_config['password'][$r]) ? $_config['password'][$r] : $_config['password'][0],
  1198. 'hostname' => isset($_config['hostname'][$r]) ? $_config['hostname'][$r] : $_config['hostname'][0],
  1199. 'hostport' => isset($_config['hostport'][$r]) ? $_config['hostport'][$r] : $_config['hostport'][0],
  1200. 'database' => isset($_config['database'][$r]) ? $_config['database'][$r] : $_config['database'][0],
  1201. 'dsn' => isset($_config['dsn'][$r]) ? $_config['dsn'][$r] : $_config['dsn'][0],
  1202. 'charset' => isset($_config['charset'][$r]) ? $_config['charset'][$r] : $_config['charset'][0],
  1203. );
  1204. return $this->connect($db_config, $r, $r == $m ? false : $db_master);
  1205. }
  1206. /**
  1207. * 析构方法
  1208. * @access public
  1209. */
  1210. public function __destruct()
  1211. {
  1212. // 释放查询
  1213. if ($this->PDOStatement) {
  1214. $this->free();
  1215. }
  1216. // 关闭连接
  1217. $this->close();
  1218. }
  1219. }