model.php 38 KB

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