model.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. Log::record("Select Sql: ".$sql, Log::ERR);
  631. //if ($options['cache'] !== false)
  632. if ($options['cache'] === true)
  633. {
  634. $key = is_string($_cache['cache_key']) ? $_cache['cache_key'] : md5($sql);
  635. if (isset($_cache[$key])){
  636. return $_cache[$key];
  637. }
  638. }
  639. $result = DB::getAll($sql,($options['lock'] === true || $options['master'] === true || defined('TRANS_MASTER')) ? 'master' : 'slave');
  640. if ($options['cache'] === true && !isset($_cache[$key])){
  641. $_cache[$key] = $result;
  642. }
  643. return $result;
  644. }
  645. public function buildSelectSql($options=array())
  646. {
  647. if (is_numeric($options['page']))
  648. {
  649. $page = pagecmd('obj');
  650. if ($options['limit'] !== 1){
  651. $options['limit'] = $page->getLimitStart().",".$page->getEachNum();
  652. }
  653. }
  654. $sql = $this->parseSql($this->selectSql,$options);
  655. $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
  656. return $sql;
  657. }
  658. public function parseSql($sql,$options=array())
  659. {
  660. $sql = str_replace(
  661. array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%INDEX%'),
  662. array(
  663. $this->parseTable($options),
  664. $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
  665. $this->parseField(isset($options['field'])?$options['field']:'*'),
  666. $this->parseJoin(isset($options['on'])?$options:array()),
  667. $this->parseWhere(isset($options['where'])?$options['where']:''),
  668. $this->parseGroup(isset($options['group'])?$options['group']:''),
  669. $this->parseHaving(isset($options['having'])?$options['having']:''),
  670. $this->parseOrder(isset($options['order'])?$options['order']:''),
  671. $this->parseLimit(isset($options['limit'])?$options['limit']:''),
  672. $this->parseUnion(isset($options['union'])?$options['union']:''),
  673. $this->parseIndex(isset($options['index'])?$options['index']:'')
  674. ),$sql);
  675. return $sql;
  676. }
  677. protected function parseUnion(){
  678. return '';
  679. }
  680. protected function parseLock($lock=false) {
  681. if(!$lock) return '';
  682. return ' FOR UPDATE ';
  683. }
  684. protected function parseIndex($value){
  685. return empty($value) ? '':' USE INDEX ('.$value.') ';
  686. }
  687. protected function parseValue($value)
  688. {
  689. if(is_string($value) || is_numeric($value)) {
  690. $value = '\''.$this->escapeString($value).'\'';
  691. }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
  692. $value = $value[1];
  693. }elseif(is_array($value)) {
  694. $value = array_map(array($this, 'parseValue'),$value);
  695. }elseif(is_null($value)){
  696. $value = 'NULL';
  697. }
  698. return $value;
  699. }
  700. protected function parseField($fields)
  701. {
  702. if(is_string($fields) && strpos($fields,',')) {
  703. $fields = explode(',',$fields);
  704. }
  705. if(is_array($fields))
  706. {
  707. //字段别名定义
  708. $array = array();
  709. foreach ($fields as $key=>$field){
  710. if(!is_numeric($key))
  711. $array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
  712. else
  713. $array[] = $this->parseKey($field);
  714. }
  715. $fieldsStr = implode(',', $array);
  716. }
  717. elseif (is_string($fields) && !empty($fields)) {
  718. $fieldsStr = $this->parseKey($fields);
  719. }
  720. else {
  721. $fieldsStr = '*';
  722. }
  723. return $fieldsStr;
  724. }
  725. protected function parseTable($options)
  726. {
  727. if ($options['on']) return null;
  728. $tables = $options['table'];
  729. if(is_array($tables)) {// 别名定义
  730. $array = array();
  731. foreach ($tables as $table=>$alias){
  732. if(!is_numeric($table))
  733. $array[] = $this->parseKey($table).' '.$this->parseKey($alias);
  734. else
  735. $array[] = $this->parseKey($table);
  736. }
  737. $tables = $array;
  738. }
  739. elseif(is_string($tables))
  740. {
  741. $tables = explode(',',$tables);
  742. array_walk($tables, array(&$this, 'parseKey'));
  743. // if (strpos($options['table'],',') === false){
  744. // $tables = $options['table'].' AS '.$options['table'];
  745. // }
  746. // $tables = explode(',',$tables);
  747. }
  748. return implode(',',$tables);
  749. }
  750. protected function parseWhere($where)
  751. {
  752. $whereStr = '';
  753. if(is_string($where)) {
  754. $whereStr = $where;
  755. }
  756. elseif(is_array($where))
  757. {
  758. if(isset($where['_op'])) {
  759. // 定义逻辑运算规则 例如 OR XOR AND NOT
  760. $operate = ' '.strtoupper($where['_op']).' ';
  761. unset($where['_op']);
  762. } else {
  763. $operate = ' AND ';
  764. }
  765. foreach ($where as $key=>$val)
  766. {
  767. // $whereStr .= '( ';
  768. // if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
  769. // $error = 'Model Error: args '.$key.' is wrong!';
  770. // throw_exception($error);
  771. // }
  772. // $key = trim($key);
  773. // $whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
  774. // $whereStr .= ' )'.$operate;
  775. $whereStrTemp = '';
  776. if(0===strpos($key,'_')) {
  777. // 解析特殊条件表达式
  778. // $whereStr .= $this->parseThinkWhere($key,$val);
  779. }
  780. else
  781. {
  782. // 查询字段的安全过滤
  783. if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
  784. throw_exception($error);
  785. }
  786. // 多条件支持
  787. $multi = is_array($val) && isset($val['_multi']);
  788. $key = trim($key);
  789. if(strpos($key,'|'))
  790. { // 支持 name|title|nickname 方式定义查询字段
  791. $array = explode('|',$key);
  792. $str = array();
  793. foreach ($array as $m=>$k){
  794. $v = $multi?$val[$m]:$val;
  795. $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
  796. }
  797. $whereStrTemp .= implode(' OR ',$str);
  798. }
  799. elseif(strpos($key,'&'))
  800. {
  801. $array = explode('&',$key);
  802. $str = array();
  803. foreach ($array as $m=>$k){
  804. $v = $multi?$val[$m]:$val;
  805. $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
  806. }
  807. $whereStrTemp .= implode(' AND ',$str);
  808. }
  809. else
  810. {
  811. $whereStrTemp .= $this->parseWhereItem($this->parseKey($key),$val);
  812. }
  813. }
  814. if(!empty($whereStrTemp)) {
  815. $whereStr .= '( '.$whereStrTemp.' )'.$operate;
  816. }
  817. }
  818. $whereStr = substr($whereStr,0,-strlen($operate));
  819. }
  820. return empty($whereStr)?'':' WHERE '.$whereStr;
  821. }
  822. // where子单元分析
  823. protected function parseWhereItem($key,$val)
  824. {
  825. $whereStr = '';
  826. if(is_array($val))
  827. {
  828. if(is_string($val[0]))
  829. {
  830. if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
  831. $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
  832. }
  833. elseif('exp'==strtolower($val[0])){ // 使用表达式
  834. // $whereStr .= ' ('.$key.' '.$val[1].') ';
  835. $whereStr .= $val[1];
  836. }
  837. elseif(preg_match('/IN/i',$val[0]))
  838. { // IN 运算
  839. if(isset($val[2]) && 'exp'==$val[2]) {
  840. $whereStr .= $key.' '.strtoupper($val[0]).' '.$val[1];
  841. }
  842. else
  843. {
  844. if (empty($val[1])){
  845. $whereStr .= $key.' '.strtoupper($val[0]).'(\'\')';
  846. }elseif(is_string($val[1]) || is_numeric($val[1])) {
  847. $val[1] = explode(',',$val[1]);
  848. $zone = implode(',',$this->parseValue($val[1]));
  849. $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
  850. }elseif(is_array($val[1])){
  851. $zone = implode(',',$this->parseValue($val[1]));
  852. $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
  853. }
  854. }
  855. }
  856. elseif(preg_match('/BETWEEN/i',$val[0]))
  857. {
  858. $data = is_string($val[1])? explode(',',$val[1]):$val[1];
  859. if($data[0] && $data[1]) {
  860. $whereStr .= ' ('.$key.' '.strtoupper($val[0]).' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]).' )';
  861. } elseif ($data[0]) {
  862. $whereStr .= $key.' '.$this->comparison['gt'].' '.$this->parseValue($data[0]);
  863. } elseif ($data[1]) {
  864. $whereStr .= $key.' '.$this->comparison['lt'].' '.$this->parseValue($data[1]);
  865. }
  866. }
  867. elseif(preg_match('/TIME/i',$val[0]))
  868. {
  869. $data = is_string($val[1])? explode(',',$val[1]):$val[1];
  870. if($data[0] && $data[1]) {
  871. $whereStr .= ' ('.$key.' BETWEEN '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1] + 86400 -1).' )';
  872. } elseif ($data[0]) {
  873. $whereStr .= $key.' '.$this->comparison['gt'].' '.$this->parseValue($data[0]);
  874. } elseif ($data[1]) {
  875. $whereStr .= $key.' '.$this->comparison['lt'].' '.$this->parseValue($data[1] + 86400);
  876. }
  877. }
  878. else{
  879. $error = 'Model Error: args '.$val[0].' is error!';
  880. throw_exception($error);
  881. }
  882. }
  883. else
  884. {
  885. $count = count($val);
  886. if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
  887. $rule = strtoupper(trim($val[$count-1]));
  888. $count = $count -1;
  889. }else{
  890. $rule = 'AND';
  891. }
  892. for($i=0;$i<$count;$i++)
  893. {
  894. if (is_array($val[$i]))
  895. {
  896. if (is_array($val[$i][1])){
  897. $data = implode(',',$val[$i][1]);
  898. }else{
  899. $data = $val[$i][1];
  900. }
  901. }
  902. else {
  903. $data = $val[$i];
  904. }
  905. if('exp'==strtolower($val[$i][0])) {
  906. $whereStr .= '('.$key.' '.$data.') '.$rule.' ';
  907. }
  908. else
  909. {
  910. $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
  911. if(preg_match('/IN/i',$op)){
  912. $whereStr .= '('.$key.' '.$op.' ('.$this->parseValue($data).')) '.$rule.' ';
  913. }else{
  914. $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
  915. }
  916. }
  917. }
  918. $whereStr = substr($whereStr,0,-4);
  919. }
  920. }
  921. else
  922. {
  923. $whereStr .= $key.' = '.$this->parseValue($val);
  924. }
  925. return $whereStr;
  926. }
  927. protected function parseLimit($limit) {
  928. return !empty($limit)? ' LIMIT '.$limit.' ':'';
  929. }
  930. protected function parseJoin($options = array())
  931. {
  932. $joinStr = '';
  933. if (false === strpos($options['table'],',')) return null;
  934. $table = explode(',',$options['table']);
  935. $on = explode(',',$options['on']);
  936. $join = $options['join'];
  937. $joinStr .= $table[0];
  938. for($i=0;$i<(count($table)-1);$i++) {
  939. $joinStr .= ' '.($join[$i]?$join[$i]:'LEFT JOIN').' '.$table[$i+1].' ON '.($on[$i]?$on[$i]:'');
  940. }
  941. return $joinStr;
  942. }
  943. public function delete($options=array())
  944. {
  945. $sql = 'DELETE '.$this->parseAttr($options).' FROM '
  946. .$this->parseTable($options)
  947. .$this->parseWhere(isset($options['where'])?$options['where']:'')
  948. .$this->parseOrder(isset($options['order'])?$options['order']:'')
  949. .$this->parseLimit(isset($options['limit'])?$options['limit']:'');
  950. if (stripos($sql,'where') === false && $options['where'] !== true){
  951. //防止条件传错,删除所有记录
  952. return false;
  953. }
  954. return DB::execute($sql);
  955. }
  956. public function update($data,$options)
  957. {
  958. $sql = 'UPDATE '
  959. .$this->parseAttr($options)
  960. .$this->parseTable($options)
  961. .$this->parseSet($data)
  962. .$this->parseWhere(isset($options['where'])?$options['where']:'')
  963. .$this->parseOrder(isset($options['order'])?$options['order']:'')
  964. .$this->parseLimit(isset($options['limit'])?$options['limit']:'');
  965. if (stripos($sql,'where') === false && $options['where'] !== true) {
  966. //防止条件传错,更新所有记录
  967. return false;
  968. }
  969. return DB::execute($sql);
  970. }
  971. public function parseAttr($options)
  972. {
  973. if (isset($options['attr']))
  974. {
  975. if (in_array(isset($options['attr']),array('LOW_PRIORITY','QUICK','IGNORE','HIGH_PRIORITY','SQL_CACHE','SQL_NO_CACHE'))){
  976. return $options['attr'].' ';
  977. }
  978. } else {
  979. return '';
  980. }
  981. }
  982. public function lockAttr($options)
  983. {
  984. if (isset($options['attr']))
  985. {
  986. if (in_array($options['attr'],array('FOR UPDATE'))){
  987. return ' '.$options['attr'].' ';
  988. }
  989. } else {
  990. return '';
  991. }
  992. }
  993. /**
  994. * 清空表
  995. *
  996. * @param array $options
  997. * @return boolean
  998. */
  999. public function clear($options)
  1000. {
  1001. $sql = 'TRUNCATE TABLE '.$this->parseTable($options);
  1002. return DB::execute($sql);
  1003. }
  1004. public function insert($data,$options=array(),$replace=false)
  1005. {
  1006. $values = $fields = array();
  1007. foreach ($data as $key=>$val)
  1008. {
  1009. $value = $this->parseValue($val);
  1010. if(is_scalar($value)) {
  1011. $values[] = $value;
  1012. $fields[] = $this->parseKey($key);
  1013. }
  1014. }
  1015. $sql = ($replace?'REPLACE ':'INSERT ').$this->parseAttr($options).' INTO '.$this->parseTable($options).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
  1016. return DB::execute($sql);
  1017. }
  1018. public function getLastId() {
  1019. return DB::getLastId();
  1020. }
  1021. /**
  1022. * 批量插入
  1023. *
  1024. * @param unknown_type $datas
  1025. * @param unknown_type $options
  1026. * @param unknown_type $replace
  1027. * @return unknown
  1028. */
  1029. public function insertAll($datas,$options=array(),$replace=false)
  1030. {
  1031. if(!is_array($datas[0])) return false;
  1032. $fields = array_keys($datas[0]);
  1033. array_walk($fields, array($this, 'parseKey'));
  1034. $values = array();
  1035. foreach ($datas as $data)
  1036. {
  1037. $value = array();
  1038. foreach ($data as $key=>$val){
  1039. $val = $this->parseValue($val);
  1040. if(is_scalar($val)) {
  1041. $value[] = $val;
  1042. }
  1043. }
  1044. $values[] = '('.implode(',', $value).')';
  1045. }
  1046. $sql = ($replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options).' ('.implode(',', $fields).') VALUES '.implode(',',$values);
  1047. return DB::execute($sql);
  1048. }
  1049. protected function parseOrder($order)
  1050. {
  1051. if(is_array($order))
  1052. {
  1053. $array = array();
  1054. foreach ($order as $key=>$val)
  1055. {
  1056. if(is_numeric($key)) {
  1057. $array[] = $this->parseKey($val);
  1058. }else{
  1059. $array[] = $this->parseKey($key).' '.$val;
  1060. }
  1061. }
  1062. $order = implode(',',$array);
  1063. }
  1064. return !empty($order)? ' ORDER BY '.$order:'';
  1065. }
  1066. protected function parseGroup($group) {
  1067. return !empty($group)? ' GROUP BY '.$group:'';
  1068. }
  1069. protected function parseHaving($having) {
  1070. return !empty($having)? ' HAVING '.$having:'';
  1071. }
  1072. protected function parseDistinct($distinct) {
  1073. return !empty($distinct)? ' DISTINCT '.$distinct.',' :'';
  1074. }
  1075. protected function parseSet($data) {
  1076. foreach ($data as $key=>$val){
  1077. $value = $this->parseValue($val);
  1078. if(is_scalar($value))
  1079. $set[] = $this->parseKey($key).'='.$value;
  1080. }
  1081. return ' SET '.implode(',',$set);
  1082. }
  1083. public function escapeString($str) {
  1084. $str = addslashes(stripslashes($str));//重新加斜线,防止从数据库直接读取出错
  1085. return $str;
  1086. }
  1087. protected function parseKey(&$key) {
  1088. return $key;
  1089. }
  1090. public function checkActive($host) {
  1091. Db::ping($host);
  1092. }
  1093. }
  1094. ?>