model.php 38 KB

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