Driver.class.php 41 KB

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