Driver.class.php 41 KB

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