model.php 41 KB

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