model.php 40 KB

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