Lite.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. class Lite {
  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. );
  59. // 数据库表达式
  60. protected $comparison = array('eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE','in'=>'IN','notin'=>'NOT IN');
  61. // 查询表达式
  62. protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%COMMENT%';
  63. // 查询次数
  64. protected $queryTimes = 0;
  65. // 执行次数
  66. protected $executeTimes = 0;
  67. // PDO连接参数
  68. protected $options = array(
  69. PDO::ATTR_CASE => PDO::CASE_LOWER,
  70. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  71. PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
  72. PDO::ATTR_STRINGIFY_FETCHES => false,
  73. );
  74. /**
  75. * 架构函数 读取数据库配置信息
  76. * @access public
  77. * @param array $config 数据库配置数组
  78. */
  79. public function __construct($config=''){
  80. if(!empty($config)) {
  81. $this->config = array_merge($this->config,$config);
  82. if(is_array($this->config['params'])){
  83. $this->options += $this->config['params'];
  84. }
  85. }
  86. }
  87. /**
  88. * 连接数据库方法
  89. * @access public
  90. */
  91. public function connect($config='',$linkNum=0) {
  92. if ( !isset($this->linkID[$linkNum]) ) {
  93. if(empty($config)) $config = $this->config;
  94. try{
  95. if(empty($config['dsn'])) {
  96. $config['dsn'] = $this->parseDsn($config);
  97. }
  98. if(version_compare(PHP_VERSION,'5.3.6','<=')){ //禁用模拟预处理语句
  99. $this->options[PDO::ATTR_EMULATE_PREPARES] = false;
  100. }
  101. $this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$this->options);
  102. }catch (\PDOException $e) {
  103. E($e->getMessage());
  104. }
  105. }
  106. return $this->linkID[$linkNum];
  107. }
  108. /**
  109. * 解析pdo连接的dsn信息
  110. * @access public
  111. * @param array $config 连接信息
  112. * @return string
  113. */
  114. protected function parseDsn($config){}
  115. /**
  116. * 释放查询结果
  117. * @access public
  118. */
  119. public function free() {
  120. $this->PDOStatement = null;
  121. }
  122. /**
  123. * 执行查询 返回数据集
  124. * @access public
  125. * @param string $str sql指令
  126. * @param array $bind 参数绑定
  127. * @return mixed
  128. */
  129. public function query($str,$bind=array()) {
  130. $this->initConnect(false);
  131. if ( !$this->_linkID ) return false;
  132. $this->queryStr = $str;
  133. if(!empty($bind)){
  134. $that = $this;
  135. $this->queryStr = strtr($this->queryStr,array_map(function($val) use($that){ return '\''.$that->escapeString($val).'\''; },$bind));
  136. }
  137. //释放前次的查询结果
  138. if ( !empty($this->PDOStatement) ) $this->free();
  139. $this->queryTimes++;
  140. N('db_query',1); // 兼容代码
  141. // 调试开始
  142. $this->debug(true);
  143. $this->PDOStatement = $this->_linkID->prepare($str);
  144. if(false === $this->PDOStatement)
  145. E($this->error());
  146. foreach ($bind as $key => $val) {
  147. if(is_array($val)){
  148. $this->PDOStatement->bindValue($key, $val[0], $val[1]);
  149. }else{
  150. $this->PDOStatement->bindValue($key, $val);
  151. }
  152. }
  153. $result = $this->PDOStatement->execute();
  154. // 调试结束
  155. $this->debug(false);
  156. if ( false === $result ) {
  157. $this->error();
  158. return false;
  159. } else {
  160. return $this->getResult();
  161. }
  162. }
  163. /**
  164. * 执行语句
  165. * @access public
  166. * @param string $str sql指令
  167. * @param array $bind 参数绑定
  168. * @return integer
  169. */
  170. public function execute($str,$bind=array()) {
  171. $this->initConnect(true);
  172. if ( !$this->_linkID ) return false;
  173. $this->queryStr = $str;
  174. if(!empty($bind)){
  175. $that = $this;
  176. $this->queryStr = strtr($this->queryStr,array_map(function($val) use($that){ return '\''.$that->escapeString($val).'\''; },$bind));
  177. }
  178. //释放前次的查询结果
  179. if ( !empty($this->PDOStatement) ) $this->free();
  180. $this->executeTimes++;
  181. N('db_write',1); // 兼容代码
  182. // 记录开始执行时间
  183. $this->debug(true);
  184. $this->PDOStatement = $this->_linkID->prepare($str);
  185. if(false === $this->PDOStatement) {
  186. E($this->error());
  187. }
  188. foreach ($bind as $key => $val) {
  189. if(is_array($val)){
  190. $this->PDOStatement->bindValue($key, $val[0], $val[1]);
  191. }else{
  192. $this->PDOStatement->bindValue($key, $val);
  193. }
  194. }
  195. $result = $this->PDOStatement->execute();
  196. $this->debug(false);
  197. if ( false === $result) {
  198. $this->error();
  199. return false;
  200. } else {
  201. $this->numRows = $this->PDOStatement->rowCount();
  202. if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
  203. $this->lastInsID = $this->_linkID->lastInsertId();
  204. }
  205. return $this->numRows;
  206. }
  207. }
  208. /**
  209. * 启动事务
  210. * @access public
  211. * @return void
  212. */
  213. public function startTrans() {
  214. $this->initConnect(true);
  215. if ( !$this->_linkID ) return false;
  216. //数据rollback 支持
  217. if ($this->transTimes == 0) {
  218. $this->_linkID->beginTransaction();
  219. }
  220. $this->transTimes++;
  221. return ;
  222. }
  223. /**
  224. * 用于非自动提交状态下面的查询提交
  225. * @access public
  226. * @return boolean
  227. */
  228. public function commit() {
  229. if ($this->transTimes > 0) {
  230. $result = $this->_linkID->commit();
  231. $this->transTimes = 0;
  232. if(!$result){
  233. $this->error();
  234. return false;
  235. }
  236. }
  237. return true;
  238. }
  239. /**
  240. * 事务回滚
  241. * @access public
  242. * @return boolean
  243. */
  244. public function rollback() {
  245. if ($this->transTimes > 0) {
  246. $result = $this->_linkID->rollback();
  247. $this->transTimes = 0;
  248. if(!$result){
  249. $this->error();
  250. return false;
  251. }
  252. }
  253. return true;
  254. }
  255. /**
  256. * 获得所有的查询数据
  257. * @access private
  258. * @return array
  259. */
  260. private function getResult() {
  261. //返回数据集
  262. $result = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
  263. $this->numRows = count( $result );
  264. return $result;
  265. }
  266. /**
  267. * 获得查询次数
  268. * @access public
  269. * @param boolean $execute 是否包含所有查询
  270. * @return integer
  271. */
  272. public function getQueryTimes($execute=false){
  273. return $execute?$this->queryTimes+$this->executeTimes:$this->queryTimes;
  274. }
  275. /**
  276. * 获得执行次数
  277. * @access public
  278. * @return integer
  279. */
  280. public function getExecuteTimes(){
  281. return $this->executeTimes;
  282. }
  283. /**
  284. * 关闭数据库
  285. * @access public
  286. */
  287. public function close() {
  288. $this->_linkID = null;
  289. }
  290. /**
  291. * 数据库错误信息
  292. * 并显示当前的SQL语句
  293. * @access public
  294. * @return string
  295. */
  296. public function error() {
  297. if($this->PDOStatement) {
  298. $error = $this->PDOStatement->errorInfo();
  299. $this->error = $error[1].':'.$error[2];
  300. }else{
  301. $this->error = '';
  302. }
  303. if('' != $this->queryStr){
  304. $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
  305. }
  306. // 记录错误日志
  307. trace($this->error,'','ERR');
  308. if($this->config['debug']) {// 开启数据库调试模式
  309. E($this->error);
  310. }else{
  311. return $this->error;
  312. }
  313. }
  314. /**
  315. * 获取最近一次查询的sql语句
  316. * @param string $model 模型名
  317. * @access public
  318. * @return string
  319. */
  320. public function getLastSql($model='') {
  321. return $model?$this->modelSql[$model]:$this->queryStr;
  322. }
  323. /**
  324. * 获取最近插入的ID
  325. * @access public
  326. * @return string
  327. */
  328. public function getLastInsID() {
  329. return $this->lastInsID;
  330. }
  331. /**
  332. * 获取最近的错误信息
  333. * @access public
  334. * @return string
  335. */
  336. public function getError() {
  337. return $this->error;
  338. }
  339. /**
  340. * SQL指令安全过滤
  341. * @access public
  342. * @param string $str SQL字符串
  343. * @return string
  344. */
  345. public function escapeString($str) {
  346. return addslashes($str);
  347. }
  348. /**
  349. * 设置当前操作模型
  350. * @access public
  351. * @param string $model 模型名
  352. * @return void
  353. */
  354. public function setModel($model){
  355. $this->model = $model;
  356. }
  357. /**
  358. * 数据库调试 记录当前SQL
  359. * @access protected
  360. * @param boolean $start 调试开始标记 true 开始 false 结束
  361. */
  362. protected function debug($start) {
  363. if($this->config['debug']) {// 开启数据库调试模式
  364. if($start) {
  365. G('queryStartTime');
  366. }else{
  367. $this->modelSql[$this->model] = $this->queryStr;
  368. //$this->model = '_think_';
  369. // 记录操作结束时间
  370. G('queryEndTime');
  371. trace($this->queryStr.' [ RunTime:'.G('queryStartTime','queryEndTime').'s ]','','SQL');
  372. }
  373. }
  374. }
  375. /**
  376. * 初始化数据库连接
  377. * @access protected
  378. * @param boolean $master 主服务器
  379. * @return void
  380. */
  381. protected function initConnect($master=true) {
  382. if(!empty($this->config['deploy']))
  383. // 采用分布式数据库
  384. $this->_linkID = $this->multiConnect($master);
  385. else
  386. // 默认单数据库
  387. if ( !$this->_linkID ) $this->_linkID = $this->connect();
  388. }
  389. /**
  390. * 连接分布式服务器
  391. * @access protected
  392. * @param boolean $master 主服务器
  393. * @return void
  394. */
  395. protected function multiConnect($master=false) {
  396. // 分布式数据库配置解析
  397. $_config['username'] = explode(',',$this->config['username']);
  398. $_config['password'] = explode(',',$this->config['password']);
  399. $_config['hostname'] = explode(',',$this->config['hostname']);
  400. $_config['hostport'] = explode(',',$this->config['hostport']);
  401. $_config['database'] = explode(',',$this->config['database']);
  402. $_config['dsn'] = explode(',',$this->config['dsn']);
  403. $_config['charset'] = explode(',',$this->config['charset']);
  404. // 数据库读写是否分离
  405. if($this->config['rw_separate']){
  406. // 主从式采用读写分离
  407. if($master)
  408. // 主服务器写入
  409. $r = floor(mt_rand(0,$this->config['master_num']-1));
  410. else{
  411. if(is_numeric($this->config['slave_no'])) {// 指定服务器读
  412. $r = $this->config['slave_no'];
  413. }else{
  414. // 读操作连接从服务器
  415. $r = floor(mt_rand($this->config['master_num'],count($_config['hostname'])-1)); // 每次随机连接的数据库
  416. }
  417. }
  418. }else{
  419. // 读写操作不区分服务器
  420. $r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库
  421. }
  422. $db_config = array(
  423. 'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
  424. 'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
  425. 'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
  426. 'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
  427. 'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
  428. 'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
  429. 'charset' => isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0],
  430. );
  431. return $this->connect($db_config,$r);
  432. }
  433. /**
  434. * 析构方法
  435. * @access public
  436. */
  437. public function __destruct() {
  438. // 释放查询
  439. if ($this->PDOStatement){
  440. $this->free();
  441. }
  442. // 关闭连接
  443. $this->close();
  444. }
  445. }