model.php 40 KB

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