model.php 40 KB

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