model.php 37 KB

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