model.php 40 KB

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