model.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. <?php
  2. declare(strict_types=0);
  3. /**
  4. * 核心文件
  5. *
  6. * 模型类
  7. */
  8. class trans_wapper
  9. {
  10. private $mMod;
  11. private $mName;
  12. private $mStart;
  13. private $mState;
  14. public function __construct($mod,$name)
  15. {
  16. $this->mName = $name;
  17. $this->mMod = $mod;
  18. $this->mState = 0;
  19. $this->begin();
  20. }
  21. private function begin()
  22. {
  23. $this->mState |= 0x0001;
  24. $this->mStart = microtime(true);
  25. if($this->mMod == null) {
  26. Db::beginTransaction();
  27. } else {
  28. $this->mMod->beginTransaction();
  29. }
  30. Log::record("trans_wapper begin {$this->mName}",Log::DEBUG);
  31. }
  32. public function commit()
  33. {
  34. $this->mState |= 0x0010;
  35. if($this->mMod == null) {
  36. Db::commit();
  37. } else {
  38. $this->mMod->commit();
  39. }
  40. $msg = sprintf("trans_wapper commit {$this->mName} use_time=%.6f",microtime(true) - $this->mStart);
  41. Log::record($msg,Log::DEBUG);
  42. }
  43. public function rollback()
  44. {
  45. $this->mState |= 0x0100;
  46. $this->mStart = microtime(true);
  47. if($this->mMod == null) {
  48. Db::rollback();
  49. } else {
  50. $this->mMod->rollback();
  51. }
  52. $msg = sprintf("trans_wapper rollback {$this->mName} use_time=%.6f",microtime(true) - $this->mStart);
  53. Log::record($msg,Log::DEBUG);
  54. }
  55. public function __destruct()
  56. {
  57. if($this->mState <= 1) {
  58. $msg = sprintf("trans_wapper uncommit or unrollback {$this->mName} state={$this->mState} use_time=%.6f",microtime(true) - $this->mStart);
  59. Log::record($msg,Log::ERR);
  60. }
  61. }
  62. }
  63. class Model
  64. {
  65. protected $name = '';
  66. protected $table_prefix = '';
  67. protected $init_table = null;
  68. protected $table_name = '';
  69. protected $options = [];
  70. protected $pk = 'id';
  71. protected $db = null;
  72. protected $fields = [];
  73. protected $unoptions = true; //是否清空参数项,默认清除
  74. public function __construct($table = null)
  75. {
  76. if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
  77. CoMysqliPool::instance()->get(Co::getCid());
  78. }
  79. $this->table_prefix = DBPRE;
  80. $this->init($table);
  81. }
  82. public function __destruct()
  83. {
  84. if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
  85. CoMysqliPool::instance()->put(Co::getCid());
  86. }
  87. }
  88. public function init($table)
  89. {
  90. $this->options = [];
  91. $this->fields = [];
  92. if (!is_null($table)){
  93. $this->table_name = $table;
  94. $this->tableInfo($table);
  95. }
  96. if (!is_object($this->db)){
  97. $this->db = new ModelDb();
  98. }
  99. }
  100. /**
  101. * 删除表主键缓存
  102. * @throws Exception
  103. */
  104. public static function dropTablePkArrayCache()
  105. {
  106. dkcache('field/_pk');
  107. }
  108. /**
  109. * 生成表结构信息
  110. *
  111. * @param string $table
  112. * @return
  113. * @throws Exception
  114. */
  115. public function tableInfo($table)
  116. {
  117. if (empty($table)) return false;
  118. //只取主键,find(2)等自动匹配主键时使用
  119. static $stFields = null;
  120. if($stFields == null)
  121. {
  122. if (C('cache_open')) {
  123. $stFields = rkcache('field/_pk', __CLASS__ . '::fetchTablePkArray');
  124. }
  125. else
  126. {
  127. $file_path = BASE_DATA_PATH . '/cache/fields/_pk.php';
  128. if (file_exists($file_path)){
  129. $stFields = require($file_path);
  130. } else {
  131. $_pk_array = self::fetchTablePkArray();
  132. F('_pk', $_pk_array, 'cache/fields');
  133. $stFields = $_pk_array;
  134. }
  135. }
  136. }
  137. $this->fields = $stFields;
  138. return true;
  139. }
  140. public static function fetchTablePkArray()
  141. {
  142. $full_table = Db::showTables();
  143. $_pk_array = [];
  144. $count = strlen(C('tablepre'));
  145. foreach ($full_table as $v_table) {
  146. $v = array_values($v_table);
  147. if (substr($v[0],0,$count) != C('tablepre')) continue;
  148. $tb = preg_replace('/^'.C('tablepre').'/', '', $v[0]);
  149. $fields = DB::showColumns($tb);
  150. foreach ((array)$fields as $k=>$v) {
  151. if($v['primary']) {
  152. $_pk_array[$tb] = $k;break;
  153. }
  154. }
  155. }
  156. return $_pk_array;
  157. }
  158. public function __call($method,$args)
  159. {
  160. if(in_array(strtolower($method), ['table','order','where','on','limit','having','group','lock','master','distinct','index','attr','key'],true))
  161. {
  162. $this->options[strtolower($method)] = $args[0];
  163. if (strtolower($method) == 'table')
  164. {
  165. if (strpos($args[0],',') !== false)
  166. {
  167. $args[0] = explode(',',$args[0]);
  168. $this->table_name = '';
  169. foreach ((array)$args[0] as $value) {
  170. $this->tableInfo($value);
  171. }
  172. } else {
  173. $this->table_name = $args[0];
  174. $this->fields = [];
  175. $this->tableInfo($args[0]);
  176. }
  177. }
  178. return $this;
  179. }
  180. elseif(in_array(strtolower($method), ['page'],true))
  181. {
  182. if ($args[0] == null){
  183. return $this;
  184. }elseif(!is_numeric($args[0]) || $args[0] <= 0){
  185. $args[0] = 10;
  186. }
  187. if (is_numeric($args[1]) && $args[1] > 0){
  188. //page(2,30)形式,传入了每页显示数据和总记录数
  189. if ($args[0] > 0){
  190. $this->options[strtolower($method)] = $args[0];
  191. pagecmd('setEachNum', $args[0]);
  192. $this->unoptions = false;
  193. pagecmd('setTotalNum', $args[1]);
  194. return $this;
  195. }else{
  196. $args[0] = 10;
  197. }
  198. }
  199. $this->options[strtolower($method)] = $args[0];
  200. pagecmd('setEachNum', $args[0]);
  201. $this->unoptions = false;
  202. pagecmd('setTotalNum', $this->get_field('COUNT(*) AS nc_count'));
  203. return $this;
  204. }
  205. elseif(in_array(strtolower($method), ['min','max','count','sum','avg'],true))
  206. {
  207. $field = isset($args[0])?$args[0]:'*';
  208. return $this->get_field(strtoupper($method).'('.$field.') AS nc_'.$method);
  209. }
  210. elseif(strtolower($method)=='count1')
  211. {
  212. $field = isset($args[0])?$args[0]:'*';
  213. $options['field'] = ('count('.$field.') AS nc_count');
  214. $options = $this->parse_options($options);
  215. $options['limit'] = 1;
  216. $result = $this->db->select($options);
  217. if(!empty($result)) {
  218. return reset($result[0]);
  219. } else {
  220. return 0;
  221. }
  222. }
  223. elseif(strtolower(substr($method,0,6))=='getby_')
  224. {
  225. $field = substr($method,6);
  226. $where[$field] = $args[0];
  227. return $this->where($where)->find();
  228. }
  229. elseif(strtolower(substr($method,0,7))=='getfby_')
  230. {
  231. $name = substr($method,7);
  232. $where[$name] =$args[0];
  233. //getfby_方法只返回第一个字段值
  234. if (strpos($args[1],',') !== false){
  235. $args[1] = substr($args[1],0,strpos($args[1],','));
  236. }
  237. return $this->where($where)->get_field($args[1]);
  238. }
  239. else
  240. {
  241. $error = 'Model Error: Function '.$method.' is not exists!';
  242. throw_exception($error);
  243. }
  244. }
  245. /**
  246. * 查询
  247. *
  248. * @param array/int $options
  249. * @return null/array
  250. */
  251. public function select($options= [])
  252. {
  253. if(is_string($options) || is_numeric($options)) {
  254. // 默认根据主键查询
  255. $pk = $this->get_pk();
  256. if(strpos($options,',')) {
  257. $where[$pk] = ['IN',$options];
  258. }else{
  259. $where[$pk] = $this->fields[$this->table_name]['_pk_type'] == 'int' ? intval($options) : $options;
  260. }
  261. $options = [];
  262. $options['where'] = $where;
  263. }
  264. $options = $this->parse_options($options);
  265. if ($options['limit'] !== false) {
  266. if (empty($options['where']) && empty($options['limit'])){
  267. //如果无条件,默认检索30条数据
  268. $options['limit'] = 30;
  269. }elseif ($options['where'] !== true && empty($options['limit'])){
  270. //如果带WHERE,但无LIMIT,最多只检索1000条记录
  271. $options['limit'] = 1000;
  272. }
  273. }
  274. $resultSet = $this->db->select($options);
  275. if(empty($resultSet)) {
  276. return [];
  277. }
  278. if ($options['key'] != '' && is_array($resultSet))
  279. {
  280. $tmp = [];
  281. foreach ($resultSet as $value) {
  282. $tmp[$value[$options['key']]] = $value;
  283. }
  284. $resultSet = $tmp;
  285. }
  286. return $resultSet;
  287. }
  288. /**
  289. * 取得第N列内容
  290. *
  291. * @param array/int $options
  292. * @return null/array
  293. */
  294. public function getfield($col = 1)
  295. {
  296. if (intval($col)<=1) $col = 1;
  297. $options = $this->parse_options();
  298. if (empty($options['where']) && empty($options['limit'])){
  299. //如果无条件,默认检索30条数据
  300. $options['limit'] = 30;
  301. }elseif ($options['where'] !== true && empty($options['limit'])){
  302. //如果带WHERE,但无LIMIT,最多只检索1000条记录
  303. $options['limit'] = 1000;
  304. }
  305. $resultSet = $this->db->select($options);
  306. if(false === $resultSet) {
  307. return false;
  308. }
  309. if(empty($resultSet)) {
  310. return null;
  311. }
  312. $return = [];
  313. $cols = array_keys($resultSet[0]);
  314. foreach ((array)$resultSet as $k => $v) {
  315. $return[$k] = $v[$cols[$col-1]];
  316. }
  317. return $return;
  318. }
  319. protected function parse_options($options= [])
  320. {
  321. if(is_array($options)) $options = array_merge($this->options,$options);
  322. if(!isset($options['table'])){
  323. $options['table'] =$this->getTableName();
  324. }elseif(false !== strpos(trim($options['table'],', '),',')){
  325. foreach(explode(',', trim($options['table'],', ')) as $val){
  326. $tmp[] = $this->getTableName($val).' AS `'.$val.'`';
  327. }
  328. $options['table'] = implode(',',$tmp);
  329. }else{
  330. $options['table'] =$this->getTableName($options['table']);
  331. }
  332. if ($this->unoptions === true){
  333. $this->options = [];
  334. }else{
  335. $this->unoptions = true;
  336. }
  337. return $options;
  338. }
  339. public function get_field($field,$sepa=null)
  340. {
  341. $options['field'] = $field;
  342. $options = $this->parse_options($options);
  343. if(strpos($field,',')) { // 多字段
  344. $resultSet = $this->db->select($options);
  345. if(!empty($resultSet)) {
  346. $_field = explode(',', $field);
  347. $field = array_keys($resultSet[0]);
  348. $move = $_field[0]==$_field[1]?false:true;
  349. $key = array_shift($field);
  350. $key2 = array_shift($field);
  351. $cols = [];
  352. $count = count($_field);
  353. foreach ($resultSet as $result){
  354. $name = $result[$key];
  355. if($move) { // 删除键值记录
  356. unset($result[$key]);
  357. }
  358. if(2==$count) {
  359. $cols[$name] = $result[$key2];
  360. }else{
  361. $cols[$name] = is_null($sepa)?$result:implode($sepa,$result);
  362. }
  363. }
  364. return $cols;
  365. }
  366. }else{
  367. $options['limit'] = 1;
  368. $result = $this->db->select($options);
  369. if(!empty($result)) {
  370. return reset($result[0]);
  371. }
  372. }
  373. return null;
  374. }
  375. /**
  376. * 返回一条记录
  377. *
  378. * @param string/int $options
  379. * @return null/array
  380. */
  381. public function find($options=null)
  382. {
  383. if(is_numeric($options) || is_string($options)) {
  384. $where[$this->get_pk()] = $options;
  385. $options = [];
  386. $options['where'] = $where;
  387. } elseif (!empty($options)) {
  388. return false;
  389. }
  390. $options['limit'] = 1;
  391. $options = $this->parse_options($options);
  392. $result = $this->db->select($options);
  393. if(empty($result)) {
  394. return [];
  395. }
  396. return $result[0];
  397. }
  398. /**
  399. * 删除
  400. *
  401. * @param array $options
  402. * @return bool/int
  403. */
  404. public function delete($options= [])
  405. {
  406. if(is_numeric($options) || is_string($options))
  407. {
  408. // 根据主键删除记录
  409. $pk = $this->get_pk();
  410. if(strpos($options,',')) {
  411. $where[$pk] = ['IN', $options];
  412. }else{
  413. $where[$pk] = $this->fields['_pk_type'] == 'int' ? intval($options) : $options;
  414. $pkValue = $options;
  415. }
  416. $options = [];
  417. $options['where'] = $where;
  418. }
  419. $options = $this->parse_options($options);
  420. $result = $this->db->delete($options);
  421. if(false !== $result) {
  422. return true;
  423. // $data = array();
  424. // if(isset($pkValue)) $data[$pk] = $pkValue;
  425. }
  426. return $result;
  427. }
  428. /**
  429. * 更新
  430. *
  431. * @param array $data
  432. * @param array $options
  433. * @return boolean
  434. */
  435. public function update($data='',$options= [])
  436. {
  437. if(empty($data)) return false;
  438. // 分析表达式
  439. $options = $this->parse_options($options);
  440. if(!isset($options['where'])) {
  441. // 如果存在主键,自动作为更新条件
  442. if(isset($data[$this->get_pk()])) {
  443. $pk = $this->get_pk();
  444. $where[$pk] = $data[$pk];
  445. $options['where'] = $where;
  446. $pkValue = $data[$pk];
  447. unset($data[$pk]);
  448. }else{
  449. return false;
  450. }
  451. }
  452. $result = $this->db->update($data,$options);
  453. if(false !== $result) {
  454. return true;
  455. }
  456. return $result;
  457. }
  458. public function affected_rows()
  459. {
  460. return $this->db->affected_rows();
  461. }
  462. /**
  463. * 插入
  464. *
  465. * @param array $data
  466. * @param bool $replace
  467. * @param array $options
  468. * @return mixed int/false
  469. */
  470. public function insert($data='', $replace=false, $options= []) {
  471. if(empty($data)) return false;
  472. $options = $this->parse_options($options);
  473. $result = $this->db->insert($data,$options,$replace);
  474. if(false !== $result ) {
  475. $insertId = $this->getLastId();
  476. if($insertId) {
  477. return $insertId;
  478. }
  479. }
  480. return $result;
  481. }
  482. /**
  483. * 批量插入
  484. *
  485. * @param array $dataList
  486. * @param array $options
  487. * @param bool $replace
  488. * @return boolean
  489. */
  490. public function insertAll($dataList, $options=[], $replace=false){
  491. if(empty($dataList)) return false;
  492. // 分析表达式
  493. $options = $this->parse_options($options);
  494. // 写入数据到数据库
  495. $result = $this->db->insertAll($dataList,$options,$replace);
  496. if(false !== $result ) return true;
  497. return $result;
  498. }
  499. /**
  500. * 直接SQL查询,返回查询结果
  501. *
  502. * @param string $sql
  503. * @return array
  504. */
  505. public function query($sql){
  506. return DB::getAll($sql);
  507. }
  508. /**
  509. * 执行SQL,用于 更新、写入、删除操作
  510. *
  511. * @param string $sql
  512. * @return
  513. */
  514. public function execute($sql){
  515. return DB::execute($sql);
  516. }
  517. /**
  518. * 开始事务
  519. *
  520. * @param string $host
  521. */
  522. public static function beginTransaction($host = 'master'){
  523. Db::beginTransaction($host);
  524. }
  525. /**
  526. * 提交事务
  527. *
  528. * @param string $host
  529. */
  530. public static function commit($host = 'master'){
  531. Db::commit($host);
  532. }
  533. /**
  534. * 回滚事务
  535. *
  536. * @param string $host
  537. */
  538. public static function rollback($host = 'master'){
  539. Db::rollback($host);
  540. }
  541. /**
  542. * 清空表
  543. *
  544. * @return boolean
  545. */
  546. public function clear(){
  547. if (!$this->table_name && !$this->options['table']) return false;
  548. $options = $this->parse_options();
  549. return $this->db->clear($options);
  550. }
  551. /**
  552. * 取得表名
  553. *
  554. * @param string $table
  555. * @return string
  556. */
  557. protected function getTableName($table = null){
  558. if (is_null($table)){
  559. $return = '`'.$this->table_prefix.$this->table_name.'`';
  560. }else{
  561. $return = '`'.$this->table_prefix.$table.'`';
  562. }
  563. return $return;
  564. }
  565. /**
  566. * 取得最后插入的ID
  567. *
  568. * @return int
  569. */
  570. private function getLastId() {
  571. return $this->db->getLastId();
  572. }
  573. /**
  574. * 指定查询字段 支持字段排除
  575. *
  576. * @param mixed $field
  577. * @param boolean $except
  578. * @return Model
  579. */
  580. public function field($field,$except=false)
  581. {
  582. if(true === $field) {// 获取全部字段
  583. $fields = $this->getFields();
  584. $field = $fields?$fields:'*';
  585. }elseif($except) {// 字段排除
  586. if(is_string($field)) {
  587. $field = explode(',',$field);
  588. }
  589. $fields = $this->getFields();
  590. $field = $fields?array_diff($fields,$field):$field;
  591. }
  592. $this->options['field'] = $field;
  593. return $this;
  594. }
  595. /**
  596. * 取得数据表字段信息
  597. *
  598. * @return mixed
  599. */
  600. public function getFields(){
  601. if($this->fields) {
  602. $fields = $this->fields;
  603. unset($fields['_autoinc'],$fields['_pk'],$fields['_type']);
  604. return $fields;
  605. }
  606. return false;
  607. }
  608. /**
  609. * 组装join
  610. *
  611. * @param string $join
  612. * @return Model
  613. */
  614. public function join($join)
  615. {
  616. if (false !== strpos($join,',')){
  617. foreach (explode(',',$join) as $key=>$val) {
  618. if (in_array(strtolower($val), ['left','inner','right'])){
  619. $this->options['join'][] = strtoupper($val).' JOIN';
  620. }else{
  621. $this->options['join'][] = 'LEFT JOIN';
  622. }
  623. }
  624. }elseif (in_array(strtolower($join), ['left','inner','right'])){
  625. $this->options['join'][] = strtoupper($join).' JOIN';
  626. }
  627. return $this;
  628. }
  629. /**
  630. * 取得主键
  631. *
  632. * @return string
  633. */
  634. public function get_pk() {
  635. return isset($this->fields[$this->table_name])?$this->fields[$this->table_name]:$this->pk;
  636. }
  637. /**
  638. * 检查非数据字段
  639. *
  640. * @param array $data
  641. * @return array
  642. */
  643. protected function chk_field($data)
  644. {
  645. if(!empty($this->fields[$this->table_name])) {
  646. foreach ($data as $key=>$val){
  647. if(!in_array($key,$this->fields[$this->table_name],true)){
  648. unset($data[$key]);
  649. }
  650. }
  651. }
  652. return $data;
  653. }
  654. public function setInc($field, $step=1) {
  655. return $this->set_field($field, ['exp',$field.'+'.$step]);
  656. }
  657. public function setDec($field,$step=1) {
  658. return $this->set_field($field, ['exp',$field.'-'.$step]);
  659. }
  660. public function set_field($field,$value='') {
  661. if(is_array($field)) {
  662. $data = $field;
  663. }else{
  664. $data[$field] = $value;
  665. }
  666. return $this->update($data);
  667. }
  668. /**
  669. * 显示分页链接
  670. *
  671. * @param int $style 分页风格
  672. * @return string
  673. */
  674. public function showpage($style = null){
  675. return pagecmd('show',$style);
  676. }
  677. /**
  678. * 获取分页总数
  679. *
  680. * @return string
  681. */
  682. public function gettotalnum(){
  683. return pagecmd('gettotalnum');
  684. }
  685. /**
  686. * 获取总页数
  687. *
  688. * @return string
  689. */
  690. public function gettotalpage(){
  691. return pagecmd('gettotalpage');
  692. }
  693. /**
  694. * 清空MODEL中的options、table_name属性
  695. *
  696. */
  697. public function cls(){
  698. $this->options = [];
  699. $this->table_name = '';
  700. return $this;
  701. }
  702. public function checkActive($host = 'master') {
  703. $this->db->checkActive($host);
  704. }
  705. }
  706. /**
  707. * 完成模型SQL组装
  708. *
  709. * SQL Helper
  710. */
  711. class ModelDb
  712. {
  713. protected $comparison = ['eq'=>'=',
  714. 'neq'=>'<>',
  715. 'gt'=>'>',
  716. 'egt'=>'>=',
  717. 'lt'=>'<',
  718. 'elt'=>'<=',
  719. 'notlike'=>'NOT LIKE',
  720. 'like'=>'LIKE',
  721. 'in'=>'IN',
  722. 'not in'=>'NOT IN'];
  723. // 查询表达式
  724. protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%INDEX%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%';
  725. public function select($options= [])
  726. {
  727. if(is_mobile())
  728. {
  729. $sql = $this->buildSelectSql($options);
  730. $result = DB::getAll($sql,($options['lock'] === true || $options['master'] === true || defined('TRANS_MASTER')) ? 'master' : 'slave');
  731. return $result;
  732. }
  733. else
  734. {
  735. static $_cache = [];
  736. $sql = $this->buildSelectSql($options);
  737. if ($options['cache'] === true)
  738. {
  739. $key = is_string($_cache['cache_key']) ? $_cache['cache_key'] : md5($sql);
  740. if (isset($_cache[$key])) {
  741. return $_cache[$key];
  742. }
  743. }
  744. $result = DB::getAll($sql, ($options['lock'] === true || $options['master'] === true || defined('TRANS_MASTER')) ? 'master' : 'slave');
  745. if ($options['cache'] === true && !isset($_cache[$key])) {
  746. $_cache[$key] = $result;
  747. }
  748. return $result;
  749. }
  750. }
  751. public function buildSelectSql($options= [])
  752. {
  753. if (is_numeric($options['page']))
  754. {
  755. $page = pagecmd('obj');
  756. if ($options['limit'] !== 1){
  757. $options['limit'] = $page->getLimitStart().",".$page->getEachNum();
  758. }
  759. }
  760. $sql = $this->parseSql($this->selectSql,$options);
  761. $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
  762. return $sql;
  763. }
  764. public function parseSql($sql,$options= [])
  765. {
  766. $sql = str_replace(
  767. ['%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%INDEX%'],
  768. [
  769. $this->parseTable($options),
  770. $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
  771. $this->parseField(isset($options['field'])?$options['field']:'*'),
  772. $this->parseJoin(isset($options['on'])?$options: []),
  773. $this->parseWhere(isset($options['where'])?$options['where']:''),
  774. $this->parseGroup(isset($options['group'])?$options['group']:''),
  775. $this->parseHaving(isset($options['having'])?$options['having']:''),
  776. $this->parseOrder(isset($options['order'])?$options['order']:''),
  777. $this->parseLimit(isset($options['limit'])?$options['limit']:''),
  778. $this->parseUnion(isset($options['union'])?$options['union']:''),
  779. $this->parseIndex(isset($options['index'])?$options['index']:'')
  780. ],$sql);
  781. return $sql;
  782. }
  783. protected function parseUnion(){
  784. return '';
  785. }
  786. protected function parseLock($lock=false) {
  787. if(!$lock) return '';
  788. return ' FOR UPDATE ';
  789. }
  790. protected function parseIndex($value){
  791. return empty($value) ? '':' USE INDEX ('.$value.') ';
  792. }
  793. protected function parseValue($value)
  794. {
  795. //|| is_numeric($value)
  796. if(is_string($value)) {
  797. $value = '\''.$this->escapeString($value).'\'';
  798. }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp') {
  799. $value = $value[1];
  800. }elseif(is_array($value)) {
  801. $value = array_map([$this, 'parseValue'],$value);
  802. }elseif(is_null($value)){
  803. $value = 'NULL';
  804. }
  805. return $value;
  806. }
  807. protected function parseField($fields)
  808. {
  809. if(is_string($fields) && strpos($fields,',')) {
  810. $fields = explode(',',$fields);
  811. }
  812. if(is_array($fields))
  813. {
  814. //字段别名定义
  815. $array = [];
  816. foreach ($fields as $key=>$field){
  817. if(!is_numeric($key))
  818. $array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
  819. else
  820. $array[] = $this->parseKey($field);
  821. }
  822. $fieldsStr = implode(',', $array);
  823. }
  824. elseif (is_string($fields) && !empty($fields)) {
  825. $fieldsStr = $this->parseKey($fields);
  826. }
  827. else {
  828. $fieldsStr = '*';
  829. }
  830. return $fieldsStr;
  831. }
  832. protected function parseTable($options)
  833. {
  834. if (!empty($options['on'])) return null;
  835. $tables = $options['table'];
  836. if(is_array($tables)) {// 别名定义
  837. $array = [];
  838. foreach ($tables as $table=>$alias){
  839. if(!is_numeric($table))
  840. $array[] = $this->parseKey($table).' '.$this->parseKey($alias);
  841. else
  842. $array[] = $this->parseKey($table);
  843. }
  844. $tables = $array;
  845. }
  846. elseif(is_string($tables))
  847. {
  848. $tables = explode(',',$tables);
  849. array_walk($tables, array(&$this, 'parseKey'));
  850. // if (strpos($options['table'],',') === false){
  851. // $tables = $options['table'].' AS '.$options['table'];
  852. // }
  853. // $tables = explode(',',$tables);
  854. }
  855. return implode(',',$tables);
  856. }
  857. protected function parseWhere($where)
  858. {
  859. $whereStr = '';
  860. if(is_string($where)) {
  861. $whereStr = $where;
  862. }
  863. elseif(is_array($where))
  864. {
  865. if(isset($where['_op'])) {
  866. // 定义逻辑运算规则 例如 OR XOR AND NOT
  867. $operate = ' '.strtoupper($where['_op']).' ';
  868. unset($where['_op']);
  869. } else {
  870. $operate = ' AND ';
  871. }
  872. foreach ($where as $key=>$val)
  873. {
  874. // $whereStr .= '( ';
  875. // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
  876. // $error = 'Model Error: args '.$key.' is wrong!';
  877. // throw_exception($error);
  878. // }
  879. // $key = trim($key);
  880. // $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
  881. // $whereStr .= ' )'.$operate;
  882. $whereStrTemp = '';
  883. if(0===strpos($key,'_')) {
  884. // 解析特殊条件表达式
  885. // $whereStr .= $this->parseThinkWhere($key,$val);
  886. }
  887. else
  888. {
  889. // 查询字段的安全过滤
  890. if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
  891. throw_exception($error);
  892. }
  893. // 多条件支持
  894. $multi = is_array($val) && isset($val['_multi']);
  895. $key = trim($key);
  896. if(strpos($key,'|'))
  897. { // 支持 name|title|nickname 方式定义查询字段
  898. $array = explode('|',$key);
  899. $str = [];
  900. foreach ($array as $m=>$k){
  901. $v = $multi?$val[$m]:$val;
  902. $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
  903. }
  904. $whereStrTemp .= implode(' OR ',$str);
  905. }
  906. elseif(strpos($key,'&'))
  907. {
  908. $array = explode('&',$key);
  909. $str = [];
  910. foreach ($array as $m=>$k){
  911. $v = $multi?$val[$m]:$val;
  912. $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
  913. }
  914. $whereStrTemp .= implode(' AND ',$str);
  915. }
  916. else
  917. {
  918. $whereStrTemp .= $this->parseWhereItem($this->parseKey($key),$val);
  919. }
  920. }
  921. if(!empty($whereStrTemp)) {
  922. $whereStr .= '( '.$whereStrTemp.' )'.$operate;
  923. }
  924. }
  925. $whereStr = substr($whereStr,0,-strlen($operate));
  926. }
  927. return empty($whereStr)?'':' WHERE '.$whereStr;
  928. }
  929. // where子单元分析
  930. protected function parseWhereItem($key,$val)
  931. {
  932. $whereStr = '';
  933. if(is_array($val))
  934. {
  935. if(is_string($val[0]))
  936. {
  937. if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
  938. $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
  939. }
  940. elseif('exp'==strtolower($val[0])){ // 使用表达式
  941. // $whereStr .= ' ('.$key.' '.$val[1].') ';
  942. $whereStr .= $val[1];
  943. }
  944. elseif(preg_match('/IN/i',$val[0]))
  945. { // IN 运算
  946. if(isset($val[2]) && 'exp'==$val[2]) {
  947. $whereStr .= $key.' '.strtoupper($val[0]).' '.$val[1];
  948. }
  949. else
  950. {
  951. if (empty($val[1])){
  952. $whereStr .= $key.' '.strtoupper($val[0]).'(\'\')';
  953. }elseif(is_string($val[1]) || is_numeric($val[1])) {
  954. $val[1] = explode(',',$val[1]);
  955. $zone = implode(',',$this->parseValue($val[1]));
  956. $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
  957. }elseif(is_array($val[1])){
  958. $zone = implode(',',$this->parseValue($val[1]));
  959. $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
  960. }
  961. }
  962. }
  963. elseif(preg_match('/BETWEEN/i',$val[0]))
  964. {
  965. $data = is_string($val[1])? explode(',',$val[1]):$val[1];
  966. if($data[0] && $data[1]) {
  967. $whereStr .= ' ('.$key.' '.strtoupper($val[0]).' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]).' )';
  968. } elseif ($data[0]) {
  969. $whereStr .= $key.' '.$this->comparison['gt'].' '.$this->parseValue($data[0]);
  970. } elseif ($data[1]) {
  971. $whereStr .= $key.' '.$this->comparison['lt'].' '.$this->parseValue($data[1]);
  972. }
  973. }
  974. elseif(preg_match('/TIME/i',$val[0]))
  975. {
  976. $data = is_string($val[1])? explode(',',$val[1]):$val[1];
  977. if($data[0] && $data[1]) {
  978. $whereStr .= ' ('.$key.' BETWEEN '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1] + 86400 -1).' )';
  979. } elseif ($data[0]) {
  980. $whereStr .= $key.' '.$this->comparison['gt'].' '.$this->parseValue($data[0]);
  981. } elseif ($data[1]) {
  982. $whereStr .= $key.' '.$this->comparison['lt'].' '.$this->parseValue($data[1] + 86400);
  983. }
  984. }
  985. else{
  986. $error = 'Model Error: args '.$val[0].' is error!';
  987. throw_exception($error);
  988. }
  989. }
  990. else
  991. {
  992. $count = count($val);
  993. if(is_array($val[$count-1]) == false && in_array(strtoupper(trim($val[$count-1])), ['AND','OR','XOR'])) {
  994. $rule = strtoupper(trim($val[$count-1]));
  995. $count = $count -1;
  996. }else{
  997. $rule = 'AND';
  998. }
  999. for($i=0;$i<$count;$i++)
  1000. {
  1001. if (is_array($val[$i]))
  1002. {
  1003. if (is_array($val[$i][1])){
  1004. $data = implode(',',$val[$i][1]);
  1005. }else{
  1006. $data = $val[$i][1];
  1007. }
  1008. }
  1009. else {
  1010. $data = $val[$i];
  1011. }
  1012. if('exp'==strtolower($val[$i][0])) {
  1013. $whereStr .= '('.$key.' '.$data.') '.$rule.' ';
  1014. }
  1015. else
  1016. {
  1017. $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
  1018. if(preg_match('/IN/i',$op)){
  1019. $whereStr .= '('.$key.' '.$op.' ('.$this->parseValue($data).')) '.$rule.' ';
  1020. }else{
  1021. $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
  1022. }
  1023. }
  1024. }
  1025. $whereStr = substr($whereStr,0,-4);
  1026. }
  1027. }
  1028. else
  1029. {
  1030. $whereStr .= $key.' = '.$this->parseValue($val);
  1031. }
  1032. return $whereStr;
  1033. }
  1034. protected function parseLimit($limit) {
  1035. return !empty($limit)? ' LIMIT '.$limit.' ':'';
  1036. }
  1037. protected function parseJoin($options = [])
  1038. {
  1039. $joinStr = '';
  1040. if (false === strpos($options['table'],',')) return null;
  1041. $table = explode(',',$options['table']);
  1042. $on = explode(',',$options['on']);
  1043. $join = $options['join'];
  1044. $joinStr .= $table[0];
  1045. for($i=0;$i<(count($table)-1);$i++) {
  1046. $joinStr .= ' '.($join[$i]?$join[$i]:'LEFT JOIN').' '.$table[$i+1].' ON '.($on[$i]?$on[$i]:'');
  1047. }
  1048. return $joinStr;
  1049. }
  1050. public function delete($options=array())
  1051. {
  1052. $sql = 'DELETE '.$this->parseAttr($options).' FROM '
  1053. .$this->parseTable($options)
  1054. .$this->parseWhere(isset($options['where'])?$options['where']:'')
  1055. .$this->parseOrder(isset($options['order'])?$options['order']:'')
  1056. .$this->parseLimit(isset($options['limit'])?$options['limit']:'');
  1057. if (stripos($sql,'where') === false && $options['where'] !== true){
  1058. //防止条件传错,删除所有记录
  1059. return false;
  1060. }
  1061. return DB::execute($sql);
  1062. }
  1063. public function update($data,$options)
  1064. {
  1065. $sql = 'UPDATE '
  1066. .$this->parseAttr($options)
  1067. .$this->parseTable($options)
  1068. .$this->parseSet($data)
  1069. .$this->parseWhere(isset($options['where'])?$options['where']:'')
  1070. .$this->parseOrder(isset($options['order'])?$options['order']:'')
  1071. .$this->parseLimit(isset($options['limit'])?$options['limit']:'');
  1072. if (stripos($sql,'where') === false && $options['where'] !== true) {
  1073. //防止条件传错,更新所有记录
  1074. return false;
  1075. }
  1076. return DB::execute($sql);
  1077. }
  1078. public function parseAttr($options)
  1079. {
  1080. if (isset($options['attr']))
  1081. {
  1082. if (in_array(isset($options['attr']), ['LOW_PRIORITY','QUICK','IGNORE','HIGH_PRIORITY','SQL_CACHE','SQL_NO_CACHE'])){
  1083. return $options['attr'].' ';
  1084. }
  1085. } else {
  1086. return '';
  1087. }
  1088. }
  1089. public function lockAttr($options)
  1090. {
  1091. if (isset($options['attr']))
  1092. {
  1093. if (in_array($options['attr'], ['FOR UPDATE'])){
  1094. return ' '.$options['attr'].' ';
  1095. }
  1096. } else {
  1097. return '';
  1098. }
  1099. }
  1100. /**
  1101. * 清空表
  1102. *
  1103. * @param array $options
  1104. * @return boolean
  1105. */
  1106. public function clear($options)
  1107. {
  1108. $sql = 'TRUNCATE TABLE '.$this->parseTable($options);
  1109. return DB::execute($sql);
  1110. }
  1111. public function insert($data, $options= [], $replace=false)
  1112. {
  1113. $values = $fields = [];
  1114. foreach ($data as $key=>$val)
  1115. {
  1116. $value = $this->parseValue($val);
  1117. if(is_scalar($value)) {
  1118. $values[] = $value;
  1119. $fields[] = $this->parseKey($key);
  1120. }
  1121. }
  1122. $sql = ($replace?'REPLACE ':'INSERT ').$this->parseAttr($options).' INTO '.$this->parseTable($options).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
  1123. return DB::execute($sql);
  1124. }
  1125. public function getLastId() {
  1126. return DB::getLastId();
  1127. }
  1128. /**
  1129. * 批量插入
  1130. *
  1131. * @param unknown_type $datas
  1132. * @param unknown_type $options
  1133. * @param unknown_type $replace
  1134. * @return bool
  1135. */
  1136. public function insertAll($datas, $options= [], $replace=false)
  1137. {
  1138. if(!is_array($datas[0])) return false;
  1139. $fields = array_keys($datas[0]);
  1140. array_walk($fields, [$this, 'parseKey']);
  1141. $values = [];
  1142. foreach ($datas as $data)
  1143. {
  1144. $value = [];
  1145. foreach ($data as $key=>$val){
  1146. $val = $this->parseValue($val);
  1147. if(is_scalar($val)) {
  1148. $value[] = $val;
  1149. }
  1150. }
  1151. $values[] = '('.implode(',', $value).')';
  1152. }
  1153. $sql = ($replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options).' ('.implode(',', $fields).') VALUES '.implode(',',$values);
  1154. return DB::execute($sql);
  1155. }
  1156. protected function parseOrder($order)
  1157. {
  1158. if(is_array($order))
  1159. {
  1160. $array = [];
  1161. foreach ($order as $key=>$val)
  1162. {
  1163. if(is_numeric($key)) {
  1164. $array[] = $this->parseKey($val);
  1165. }else{
  1166. $array[] = $this->parseKey($key).' '.$val;
  1167. }
  1168. }
  1169. $order = implode(',',$array);
  1170. }
  1171. return !empty($order)? ' ORDER BY '.$order:'';
  1172. }
  1173. protected function parseGroup($group) {
  1174. return !empty($group)? ' GROUP BY '.$group:'';
  1175. }
  1176. protected function parseHaving($having) {
  1177. return !empty($having)? ' HAVING '.$having:'';
  1178. }
  1179. protected function parseDistinct($distinct) {
  1180. return !empty($distinct)? ' DISTINCT '.$distinct.',' :'';
  1181. }
  1182. protected function parseSet($data) {
  1183. foreach ($data as $key=>$val){
  1184. $value = $this->parseValue($val);
  1185. if(is_scalar($value))
  1186. $set[] = $this->parseKey($key).'='.$value;
  1187. }
  1188. return ' SET '.implode(',',$set);
  1189. }
  1190. public function escapeString($str) {
  1191. $str = addslashes(stripslashes($str));//重新加斜线,防止从数据库直接读取出错
  1192. return $str;
  1193. }
  1194. protected function parseKey(&$key) {
  1195. return $key;
  1196. }
  1197. public function checkActive($host) {
  1198. Db::ping($host);
  1199. }
  1200. public function affected_rows($host = 'master') {
  1201. return Db::affected_rows($host);
  1202. }
  1203. }
  1204. ?>