Driver.class.php 40 KB

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