model.php 38 KB

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