model.php 40 KB

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