model.php 40 KB

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