Driverbak.class.php 41 KB

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