model.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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 = '33hao_';//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. if(is_numeric($options) || is_string($options)) {
  315. // 根据主键删除记录
  316. $pk = $this->get_pk();
  317. if(strpos($options,',')) {
  318. $where[$pk] = array('IN', $options);
  319. }else{
  320. $where[$pk] = $this->fields['_pk_type'] == 'int' ? intval($options) : $options;
  321. $pkValue = $options;
  322. }
  323. $options = array();
  324. $options['where'] = $where;
  325. }
  326. $options = $this->parse_options($options);
  327. $result = $this->db->delete($options);
  328. if(false !== $result) {
  329. return true;
  330. // $data = array();
  331. // if(isset($pkValue)) $data[$pk] = $pkValue;
  332. }
  333. return $result;
  334. }
  335. /**
  336. * 更新
  337. *
  338. * @param array $data
  339. * @param array $options
  340. * @return boolean
  341. */
  342. public function update($data='',$options=array()) {
  343. if(empty($data)) return false;
  344. // 分析表达式
  345. $options = $this->parse_options($options);
  346. if(!isset($options['where'])) {
  347. // 如果存在主键,自动作为更新条件
  348. if(isset($data[$this->get_pk()])) {
  349. $pk = $this->get_pk();
  350. $where[$pk] = $data[$pk];
  351. $options['where'] = $where;
  352. $pkValue = $data[$pk];
  353. unset($data[$pk]);
  354. }else{
  355. return false;
  356. }
  357. }
  358. $result = $this->db->update($data,$options);
  359. if(false !== $result) {
  360. return true;
  361. }
  362. return $result;
  363. }
  364. /**
  365. * 插入
  366. *
  367. * @param array $data
  368. * @param bool $replace
  369. * @param array $options
  370. * @return mixed int/false
  371. */
  372. public function insert($data='', $replace=false, $options=array()) {
  373. if(empty($data)) return false;
  374. $options = $this->parse_options($options);
  375. $result = $this->db->insert($data,$options,$replace);
  376. if(false !== $result ) {
  377. $insertId = $this->getLastId();
  378. if($insertId) {
  379. return $insertId;
  380. }
  381. }
  382. return $result;
  383. }
  384. /**
  385. * 批量插入
  386. *
  387. * @param array $dataList
  388. * @param array $options
  389. * @param bool $replace
  390. * @return boolean
  391. */
  392. public function insertAll($dataList,$options=array(),$replace=false){
  393. if(empty($dataList)) return false;
  394. // 分析表达式
  395. $options = $this->parse_options($options);
  396. // 写入数据到数据库
  397. $result = $this->db->insertAll($dataList,$options,$replace);
  398. if(false !== $result ) return true;
  399. return $result;
  400. }
  401. /**
  402. * 直接SQL查询,返回查询结果
  403. *
  404. * @param string $sql
  405. * @return array
  406. */
  407. public function query($sql){
  408. return DB::getAll($sql);
  409. }
  410. /**
  411. * 执行SQL,用于 更新、写入、删除操作
  412. *
  413. * @param string $sql
  414. * @return
  415. */
  416. public function execute($sql){
  417. return DB::execute($sql);
  418. }
  419. /**
  420. * 开始事务
  421. *
  422. * @param string $host
  423. */
  424. public static function beginTransaction($host = 'master'){
  425. Db::beginTransaction($host);
  426. }
  427. /**
  428. * 提交事务
  429. *
  430. * @param string $host
  431. */
  432. public static function commit($host = 'master'){
  433. Db::commit($host);
  434. }
  435. /**
  436. * 回滚事务
  437. *
  438. * @param string $host
  439. */
  440. public static function rollback($host = 'master'){
  441. Db::rollback($host);
  442. }
  443. /**
  444. * 清空表
  445. *
  446. * @return boolean
  447. */
  448. public function clear(){
  449. if (!$this->table_name && !$this->options['table']) return false;
  450. $options = $this->parse_options();
  451. return $this->db->clear($options);
  452. }
  453. /**
  454. * 取得表名
  455. *
  456. * @param string $table
  457. * @return string
  458. */
  459. protected function getTableName($table = null){
  460. if (is_null($table)){
  461. $return = '`'.$this->table_prefix.$this->table_name.'`';
  462. }else{
  463. $return = '`'.$this->table_prefix.$table.'`';
  464. }
  465. return $return;
  466. }
  467. /**
  468. * 取得最后插入的ID
  469. *
  470. * @return int
  471. */
  472. public function getLastId() {
  473. return $this->db->getLastId();
  474. }
  475. /**
  476. * 指定查询字段 支持字段排除
  477. *
  478. * @param mixed $field
  479. * @param boolean $except
  480. * @return Model
  481. */
  482. public function field($field,$except=false){
  483. if(true === $field) {// 获取全部字段
  484. $fields = $this->getFields();
  485. $field = $fields?$fields:'*';
  486. }elseif($except) {// 字段排除
  487. if(is_string($field)) {
  488. $field = explode(',',$field);
  489. }
  490. $fields = $this->getFields();
  491. $field = $fields?array_diff($fields,$field):$field;
  492. }
  493. $this->options['field'] = $field;
  494. return $this;
  495. }
  496. /**
  497. * 取得数据表字段信息
  498. *
  499. * @return mixed
  500. */
  501. public function getFields(){
  502. if($this->fields) {
  503. $fields = $this->fields;
  504. unset($fields['_autoinc'],$fields['_pk'],$fields['_type']);
  505. return $fields;
  506. }
  507. return false;
  508. }
  509. /**
  510. * 组装join
  511. *
  512. * @param string $join
  513. * @return Model
  514. */
  515. public function join($join) {
  516. if (false !== strpos($join,',')){
  517. foreach (explode(',',$join) as $key=>$val) {
  518. if (in_array(strtolower($val),array('left','inner','right'))){
  519. $this->options['join'][] = strtoupper($val).' JOIN';
  520. }else{
  521. $this->options['join'][] = 'LEFT JOIN';
  522. }
  523. }
  524. }elseif (in_array(strtolower($join),array('left','inner','right'))){
  525. $this->options['join'][] = strtoupper($join).' JOIN';
  526. }
  527. return $this;
  528. }
  529. /**
  530. * 取得主键
  531. *
  532. * @return string
  533. */
  534. public function get_pk() {
  535. return isset($this->fields[$this->table_name])?$this->fields[$this->table_name]:$this->pk;
  536. }
  537. /**
  538. * 检查非数据字段
  539. *
  540. * @param array $data
  541. * @return array
  542. */
  543. protected function chk_field($data) {
  544. if(!empty($this->fields[$this->table_name])) {
  545. foreach ($data as $key=>$val){
  546. if(!in_array($key,$this->fields[$this->table_name],true)){
  547. unset($data[$key]);
  548. }
  549. }
  550. }
  551. return $data;
  552. }
  553. public function setInc($field, $step=1) {
  554. return $this->set_field($field,array('exp',$field.'+'.$step));
  555. }
  556. public function setDec($field,$step=1) {
  557. return $this->set_field($field,array('exp',$field.'-'.$step));
  558. }
  559. public function set_field($field,$value='') {
  560. if(is_array($field)) {
  561. $data = $field;
  562. }else{
  563. $data[$field] = $value;
  564. }
  565. return $this->update($data);
  566. }
  567. /**
  568. * 显示分页链接
  569. *
  570. * @param int $style 分页风格
  571. * @return string
  572. */
  573. public function showpage($style = null){
  574. return pagecmd('show',$style);
  575. }
  576. /**
  577. * 获取分页总数
  578. *
  579. * @return string
  580. */
  581. public function gettotalnum(){
  582. return pagecmd('gettotalnum');
  583. }
  584. /**
  585. * 获取总页数
  586. *
  587. * @return string
  588. */
  589. public function gettotalpage(){
  590. return pagecmd('gettotalpage');
  591. }
  592. /**
  593. * 清空MODEL中的options、table_name属性
  594. *
  595. */
  596. public function cls(){
  597. $this->options = array();
  598. $this->table_name = '';
  599. return $this;
  600. }
  601. public function checkActive($host = 'master') {
  602. $this->db->checkActive($host);
  603. }
  604. }
  605. /**
  606. * 完成模型SQL组装
  607. *
  608. * SQL Helper
  609. */
  610. class ModelDb
  611. {
  612. protected $comparison = array('eq'=>'=',
  613. 'neq'=>'<>',
  614. 'gt'=>'>',
  615. 'egt'=>'>=',
  616. 'lt'=>'<',
  617. 'elt'=>'<=',
  618. 'notlike'=>'NOT LIKE',
  619. 'like'=>'LIKE',
  620. 'in'=>'IN',
  621. 'not in'=>'NOT IN');
  622. // 查询表达式
  623. protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%INDEX%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%';
  624. public function select($options=array())
  625. {
  626. // static $_cache = array();
  627. $sql = $this->buildSelectSql($options);
  628. if ($options['cache'] !== false){
  629. $key = is_string($cache['cache_key']) ? $cache['cache_key'] : md5($sql);
  630. if (isset($_cache[$key])){
  631. return $_cache[$key];
  632. }
  633. }
  634. $result = DB::getAll($sql,($options['lock'] === true || $options['master'] === true || defined('TRANS_MASTER')) ? 'master' : 'slave');
  635. // if ($options['cache'] !== false && !isset($_cache[$key])){
  636. // $_cache[$key] = $result;
  637. // }
  638. return $result;
  639. }
  640. public function buildSelectSql($options=array())
  641. {
  642. if (is_numeric($options['page']))
  643. {
  644. $page = pagecmd('obj');
  645. if ($options['limit'] !== 1){
  646. $options['limit'] = $page->getLimitStart().",".$page->getEachNum();
  647. }
  648. }
  649. $sql = $this->parseSql($this->selectSql,$options);
  650. $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
  651. return $sql;
  652. }
  653. public function parseSql($sql,$options=array())
  654. {
  655. $sql = str_replace(
  656. array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%INDEX%'),
  657. array(
  658. $this->parseTable($options),
  659. $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
  660. $this->parseField(isset($options['field'])?$options['field']:'*'),
  661. $this->parseJoin(isset($options['on'])?$options:array()),
  662. $this->parseWhere(isset($options['where'])?$options['where']:''),
  663. $this->parseGroup(isset($options['group'])?$options['group']:''),
  664. $this->parseHaving(isset($options['having'])?$options['having']:''),
  665. $this->parseOrder(isset($options['order'])?$options['order']:''),
  666. $this->parseLimit(isset($options['limit'])?$options['limit']:''),
  667. $this->parseUnion(isset($options['union'])?$options['union']:''),
  668. $this->parseIndex(isset($options['index'])?$options['index']:'')
  669. ),$sql);
  670. return $sql;
  671. }
  672. protected function parseUnion(){
  673. return '';
  674. }
  675. protected function parseLock($lock=false) {
  676. if(!$lock) return '';
  677. return ' FOR UPDATE ';
  678. }
  679. protected function parseIndex($value){
  680. return empty($value) ? '':' USE INDEX ('.$value.') ';
  681. }
  682. protected function parseValue($value)
  683. {
  684. if(is_string($value) || is_numeric($value)) {
  685. $value = '\''.$this->escapeString($value).'\'';
  686. }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
  687. $value = $value[1];
  688. }elseif(is_array($value)) {
  689. $value = array_map(array($this, 'parseValue'),$value);
  690. }elseif(is_null($value)){
  691. $value = 'NULL';
  692. }
  693. return $value;
  694. }
  695. protected function parseField($fields)
  696. {
  697. if(is_string($fields) && strpos($fields,',')) {
  698. $fields = explode(',',$fields);
  699. }
  700. if(is_array($fields))
  701. {
  702. //字段别名定义
  703. $array = array();
  704. foreach ($fields as $key=>$field){
  705. if(!is_numeric($key))
  706. $array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
  707. else
  708. $array[] = $this->parseKey($field);
  709. }
  710. $fieldsStr = implode(',', $array);
  711. }
  712. elseif (is_string($fields) && !empty($fields)) {
  713. $fieldsStr = $this->parseKey($fields);
  714. }
  715. else {
  716. $fieldsStr = '*';
  717. }
  718. return $fieldsStr;
  719. }
  720. protected function parseTable($options)
  721. {
  722. if ($options['on']) return null;
  723. $tables = $options['table'];
  724. if(is_array($tables)) {// 别名定义
  725. $array = array();
  726. foreach ($tables as $table=>$alias){
  727. if(!is_numeric($table))
  728. $array[] = $this->parseKey($table).' '.$this->parseKey($alias);
  729. else
  730. $array[] = $this->parseKey($table);
  731. }
  732. $tables = $array;
  733. }
  734. elseif(is_string($tables))
  735. {
  736. $tables = explode(',',$tables);
  737. array_walk($tables, array(&$this, 'parseKey'));
  738. // if (strpos($options['table'],',') === false){
  739. // $tables = $options['table'].' AS '.$options['table'];
  740. // }
  741. // $tables = explode(',',$tables);
  742. }
  743. return implode(',',$tables);
  744. }
  745. protected function parseWhere($where)
  746. {
  747. $whereStr = '';
  748. if(is_string($where)) {
  749. $whereStr = $where;
  750. }
  751. elseif(is_array($where))
  752. {
  753. if(isset($where['_op'])) {
  754. // 定义逻辑运算规则 例如 OR XOR AND NOT
  755. $operate = ' '.strtoupper($where['_op']).' ';
  756. unset($where['_op']);
  757. } else {
  758. $operate = ' AND ';
  759. }
  760. foreach ($where as $key=>$val)
  761. {
  762. // $whereStr .= '( ';
  763. // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
  764. // $error = 'Model Error: args '.$key.' is wrong!';
  765. // throw_exception($error);
  766. // }
  767. // $key = trim($key);
  768. // $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
  769. // $whereStr .= ' )'.$operate;
  770. $whereStrTemp = '';
  771. if(0===strpos($key,'_')) {
  772. // 解析特殊条件表达式
  773. // $whereStr .= $this->parseThinkWhere($key,$val);
  774. }
  775. else
  776. {
  777. // 查询字段的安全过滤
  778. if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
  779. throw_exception($error);
  780. }
  781. // 多条件支持
  782. $multi = is_array($val) && isset($val['_multi']);
  783. $key = trim($key);
  784. if(strpos($key,'|'))
  785. { // 支持 name|title|nickname 方式定义查询字段
  786. $array = explode('|',$key);
  787. $str = array();
  788. foreach ($array as $m=>$k){
  789. $v = $multi?$val[$m]:$val;
  790. $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
  791. }
  792. $whereStrTemp .= implode(' OR ',$str);
  793. }
  794. elseif(strpos($key,'&'))
  795. {
  796. $array = explode('&',$key);
  797. $str = array();
  798. foreach ($array as $m=>$k){
  799. $v = $multi?$val[$m]:$val;
  800. $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
  801. }
  802. $whereStrTemp .= implode(' AND ',$str);
  803. }
  804. else
  805. {
  806. $whereStrTemp .= $this->parseWhereItem($this->parseKey($key),$val);
  807. }
  808. }
  809. if(!empty($whereStrTemp)) {
  810. $whereStr .= '( '.$whereStrTemp.' )'.$operate;
  811. }
  812. }
  813. $whereStr = substr($whereStr,0,-strlen($operate));
  814. }
  815. return empty($whereStr)?'':' WHERE '.$whereStr;
  816. }
  817. // where子单元分析
  818. protected function parseWhereItem($key,$val)
  819. {
  820. $whereStr = '';
  821. if(is_array($val))
  822. {
  823. if(is_string($val[0]))
  824. {
  825. if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
  826. $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
  827. }
  828. elseif('exp'==strtolower($val[0])){ // 使用表达式
  829. // $whereStr .= ' ('.$key.' '.$val[1].') ';
  830. $whereStr .= $val[1];
  831. }
  832. elseif(preg_match('/IN/i',$val[0]))
  833. { // IN 运算
  834. if(isset($val[2]) && 'exp'==$val[2]) {
  835. $whereStr .= $key.' '.strtoupper($val[0]).' '.$val[1];
  836. }
  837. else
  838. {
  839. if (empty($val[1])){
  840. $whereStr .= $key.' '.strtoupper($val[0]).'(\'\')';
  841. }elseif(is_string($val[1]) || is_numeric($val[1])) {
  842. $val[1] = explode(',',$val[1]);
  843. $zone = implode(',',$this->parseValue($val[1]));
  844. $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
  845. }elseif(is_array($val[1])){
  846. $zone = implode(',',$this->parseValue($val[1]));
  847. $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
  848. }
  849. }
  850. }
  851. elseif(preg_match('/BETWEEN/i',$val[0]))
  852. {
  853. $data = is_string($val[1])? explode(',',$val[1]):$val[1];
  854. if($data[0] && $data[1]) {
  855. $whereStr .= ' ('.$key.' '.strtoupper($val[0]).' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]).' )';
  856. } elseif ($data[0]) {
  857. $whereStr .= $key.' '.$this->comparison['gt'].' '.$this->parseValue($data[0]);
  858. } elseif ($data[1]) {
  859. $whereStr .= $key.' '.$this->comparison['lt'].' '.$this->parseValue($data[1]);
  860. }
  861. }
  862. elseif(preg_match('/TIME/i',$val[0]))
  863. {
  864. $data = is_string($val[1])? explode(',',$val[1]):$val[1];
  865. if($data[0] && $data[1]) {
  866. $whereStr .= ' ('.$key.' BETWEEN '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1] + 86400 -1).' )';
  867. } elseif ($data[0]) {
  868. $whereStr .= $key.' '.$this->comparison['gt'].' '.$this->parseValue($data[0]);
  869. } elseif ($data[1]) {
  870. $whereStr .= $key.' '.$this->comparison['lt'].' '.$this->parseValue($data[1] + 86400);
  871. }
  872. }
  873. else{
  874. $error = 'Model Error: args '.$val[0].' is error!';
  875. throw_exception($error);
  876. }
  877. }
  878. else
  879. {
  880. $count = count($val);
  881. if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
  882. $rule = strtoupper(trim($val[$count-1]));
  883. $count = $count -1;
  884. }else{
  885. $rule = 'AND';
  886. }
  887. for($i=0;$i<$count;$i++)
  888. {
  889. if (is_array($val[$i]))
  890. {
  891. if (is_array($val[$i][1])){
  892. $data = implode(',',$val[$i][1]);
  893. }else{
  894. $data = $val[$i][1];
  895. }
  896. }
  897. else {
  898. $data = $val[$i];
  899. }
  900. if('exp'==strtolower($val[$i][0])) {
  901. $whereStr .= '('.$key.' '.$data.') '.$rule.' ';
  902. }
  903. else
  904. {
  905. $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
  906. if(preg_match('/IN/i',$op)){
  907. $whereStr .= '('.$key.' '.$op.' ('.$this->parseValue($data).')) '.$rule.' ';
  908. }else{
  909. $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
  910. }
  911. }
  912. }
  913. $whereStr = substr($whereStr,0,-4);
  914. }
  915. }
  916. else
  917. {
  918. $whereStr .= $key.' = '.$this->parseValue($val);
  919. }
  920. return $whereStr;
  921. }
  922. protected function parseLimit($limit) {
  923. return !empty($limit)? ' LIMIT '.$limit.' ':'';
  924. }
  925. protected function parseJoin($options = array())
  926. {
  927. $joinStr = '';
  928. if (false === strpos($options['table'],',')) return null;
  929. $table = explode(',',$options['table']);
  930. $on = explode(',',$options['on']);
  931. $join = $options['join'];
  932. $joinStr .= $table[0];
  933. for($i=0;$i<(count($table)-1);$i++) {
  934. $joinStr .= ' '.($join[$i]?$join[$i]:'LEFT JOIN').' '.$table[$i+1].' ON '.($on[$i]?$on[$i]:'');
  935. }
  936. return $joinStr;
  937. }
  938. public function delete($options=array())
  939. {
  940. $sql = 'DELETE '.$this->parseAttr($options).' FROM '
  941. .$this->parseTable($options)
  942. .$this->parseWhere(isset($options['where'])?$options['where']:'')
  943. .$this->parseOrder(isset($options['order'])?$options['order']:'')
  944. .$this->parseLimit(isset($options['limit'])?$options['limit']:'');
  945. if (stripos($sql,'where') === false && $options['where'] !== true){
  946. //防止条件传错,删除所有记录
  947. return false;
  948. }
  949. return DB::execute($sql);
  950. }
  951. public function update($data,$options)
  952. {
  953. $sql = 'UPDATE '
  954. .$this->parseAttr($options)
  955. .$this->parseTable($options)
  956. .$this->parseSet($data)
  957. .$this->parseWhere(isset($options['where'])?$options['where']:'')
  958. .$this->parseOrder(isset($options['order'])?$options['order']:'')
  959. .$this->parseLimit(isset($options['limit'])?$options['limit']:'');
  960. if (stripos($sql,'where') === false && $options['where'] !== true) {
  961. //防止条件传错,更新所有记录
  962. return false;
  963. }
  964. return DB::execute($sql);
  965. }
  966. public function parseAttr($options)
  967. {
  968. if (isset($options['attr']))
  969. {
  970. if (in_array(isset($options['attr']),array('LOW_PRIORITY','QUICK','IGNORE','HIGH_PRIORITY','SQL_CACHE','SQL_NO_CACHE'))){
  971. return $options['attr'].' ';
  972. }
  973. } else {
  974. return '';
  975. }
  976. }
  977. public function lockAttr($options)
  978. {
  979. if (isset($options['attr']))
  980. {
  981. if (in_array($options['attr'],array('FOR UPDATE'))){
  982. return ' '.$options['attr'].' ';
  983. }
  984. } else {
  985. return '';
  986. }
  987. }
  988. /**
  989. * 清空表
  990. *
  991. * @param array $options
  992. * @return boolean
  993. */
  994. public function clear($options)
  995. {
  996. $sql = 'TRUNCATE TABLE '.$this->parseTable($options);
  997. return DB::execute($sql);
  998. }
  999. public function insert($data,$options=array(),$replace=false)
  1000. {
  1001. $values = $fields = array();
  1002. foreach ($data as $key=>$val)
  1003. {
  1004. $value = $this->parseValue($val);
  1005. if(is_scalar($value)) {
  1006. $values[] = $value;
  1007. $fields[] = $this->parseKey($key);
  1008. }
  1009. }
  1010. $sql = ($replace?'REPLACE ':'INSERT ').$this->parseAttr($options).' INTO '.$this->parseTable($options).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
  1011. return DB::execute($sql);
  1012. }
  1013. public function getLastId() {
  1014. return DB::getLastId();
  1015. }
  1016. /**
  1017. * 批量插入
  1018. *
  1019. * @param unknown_type $datas
  1020. * @param unknown_type $options
  1021. * @param unknown_type $replace
  1022. * @return unknown
  1023. */
  1024. public function insertAll($datas,$options=array(),$replace=false)
  1025. {
  1026. if(!is_array($datas[0])) return false;
  1027. $fields = array_keys($datas[0]);
  1028. array_walk($fields, array($this, 'parseKey'));
  1029. $values = array();
  1030. foreach ($datas as $data)
  1031. {
  1032. $value = array();
  1033. foreach ($data as $key=>$val){
  1034. $val = $this->parseValue($val);
  1035. if(is_scalar($val)) {
  1036. $value[] = $val;
  1037. }
  1038. }
  1039. $values[] = '('.implode(',', $value).')';
  1040. }
  1041. $sql = ($replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options).' ('.implode(',', $fields).') VALUES '.implode(',',$values);
  1042. return DB::execute($sql);
  1043. }
  1044. protected function parseOrder($order)
  1045. {
  1046. if(is_array($order))
  1047. {
  1048. $array = array();
  1049. foreach ($order as $key=>$val)
  1050. {
  1051. if(is_numeric($key)) {
  1052. $array[] = $this->parseKey($val);
  1053. }else{
  1054. $array[] = $this->parseKey($key).' '.$val;
  1055. }
  1056. }
  1057. $order = implode(',',$array);
  1058. }
  1059. return !empty($order)? ' ORDER BY '.$order:'';
  1060. }
  1061. protected function parseGroup($group) {
  1062. return !empty($group)? ' GROUP BY '.$group:'';
  1063. }
  1064. protected function parseHaving($having) {
  1065. return !empty($having)? ' HAVING '.$having:'';
  1066. }
  1067. protected function parseDistinct($distinct) {
  1068. return !empty($distinct)? ' DISTINCT '.$distinct.',' :'';
  1069. }
  1070. protected function parseSet($data) {
  1071. foreach ($data as $key=>$val){
  1072. $value = $this->parseValue($val);
  1073. if(is_scalar($value))
  1074. $set[] = $this->parseKey($key).'='.$value;
  1075. }
  1076. return ' SET '.implode(',',$set);
  1077. }
  1078. public function escapeString($str) {
  1079. $str = addslashes(stripslashes($str));//重新加斜线,防止从数据库直接读取出错
  1080. return $str;
  1081. }
  1082. protected function parseKey(&$key) {
  1083. return $key;
  1084. }
  1085. public function checkActive($host) {
  1086. Db::ping($host);
  1087. }
  1088. }
  1089. ?>