Driver.class.php 40 KB

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