Driver.class.php 44 KB

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