model.php 37 KB

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