model.php 40 KB

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