model.php 38 KB

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