Base.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. <?php
  2. namespace Qii\Driver;
  3. class Base
  4. {
  5. const VERSION = '1.2';
  6. public $_cache;
  7. public $language;
  8. protected $_query = array(
  9. "INSERT" => "INSERT INTO %s(%s) VALUES('%s')",
  10. "REPLACE" => "REPLACE %s (%s) VALUES('%s')",
  11. "SELECT" => "SELECT %s FROM %s",
  12. "UPDATE" => "UPDATE %s SET ",
  13. "DELETE" => "DELETE FROM %s %s",
  14. "WHERE" => " WHERE %s",
  15. "LIKE" => " `%s` LIKE '%s'",
  16. "ORDER" => " ORDER BY %s %s",
  17. "GROUP" => " GROUP BY %s",
  18. "LIMIT" => " LIMIT %d, %d"
  19. );
  20. private $query;
  21. private $setArray = array();
  22. public $modelSQL = "";
  23. protected $fields;
  24. protected $where;
  25. protected $groupBy;
  26. protected $limit;
  27. protected $orderBy;
  28. public $load;
  29. /**
  30. * @var string $_response Response对象
  31. */
  32. protected $_response;
  33. //方法对应的别名
  34. protected $_modelAlias = array('selectRows' => 'selectAll', 'select' => 'selectRow', 'getOne' => 'selectOne', 'getRow' => 'selectRow', 'getAll' => 'selectAll', 'remove' => 'deleteRows');
  35. public function __construct()
  36. {
  37. $this->language = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Language\Loader');
  38. $this->load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
  39. $this->_response = new \Qii\Driver\Response();
  40. }
  41. /**
  42. * 获取数据库中所有的数据表
  43. * @return array
  44. */
  45. public function getAllDatabases()
  46. {
  47. $sql = "SHOW DATABASES";
  48. $rs = $this->setQuery($sql);
  49. $database = array();
  50. while($row = $rs->fetch())
  51. {
  52. $database[] = $row['Database'];
  53. }
  54. return $database;
  55. }
  56. /**
  57. * 数据库中是否包含指定库
  58. * @param string $database 数据库名
  59. * @return bool
  60. */
  61. public function hasDatabase($database)
  62. {
  63. if(!$database) return false;
  64. $sql = "SHOW DATABASES LIKE '". $database ."'";
  65. $rs = $this->setQuery($sql);
  66. while($row = $rs->fetch())
  67. {
  68. $val = array_values($row);
  69. if(in_array($database, $val))
  70. {
  71. return true;
  72. }
  73. }
  74. return false;
  75. }
  76. /**
  77. * 获取当前数据库中所有的表
  78. * @param null|string $database 数据库
  79. * @return array
  80. */
  81. public function getAllTables($database = null)
  82. {
  83. if($database)
  84. {
  85. $this->setQuery('USE '. $database);
  86. }
  87. $sql = "SHOW TABLES";
  88. $rs = $this->setQuery($sql);
  89. $tables = array();
  90. while($row = $rs->fetch())
  91. {
  92. if(is_array($row)) {
  93. foreach($row AS $val) {
  94. $tables[] = $val;
  95. }
  96. }
  97. }
  98. return $tables;
  99. }
  100. /**
  101. * 获取指定数据表的所有字段
  102. * @param string $table 表名
  103. * @param string $database 数据库名
  104. * @return array
  105. */
  106. public function getTableInfo($table, $database = null)
  107. {
  108. if(!$database) $database = $this->currentDB;
  109. $sql = "SELECT * from information_schema.COLUMNS where table_name = '".$table."' and table_schema = '".$database."'";
  110. $data = ['fields' => [],
  111. 'rules' => [
  112. 'pri' => [], 'required' => []
  113. ]
  114. ];
  115. $rs = $this->setQuery($sql);
  116. while($row = $rs->fetch())
  117. {
  118. $data['fields'][] = $row['COLUMN_NAME'];
  119. if($row['EXTRA'])
  120. {
  121. $data['rules']['extra'][$row['EXTRA']][] = $row['COLUMN_NAME'];
  122. }
  123. if($row['COLUMN_KEY'] == 'PRI')
  124. {
  125. $data['rules']['pri'][] = $row['COLUMN_NAME'];
  126. $data['rules']['required'][] = $row['COLUMN_NAME'];
  127. }
  128. if($row['IS_NULLABLE'] == 'NO')
  129. {
  130. $data['rules']['required'][] = $row['COLUMN_NAME'];
  131. }
  132. if(in_array($row['DATA_TYPE'], ['varchar', 'char']))
  133. {
  134. $data['rules']['maxlength'][$row['COLUMN_NAME']] = $row['CHARACTER_MAXIMUM_LENGTH'];
  135. }
  136. if(in_array($row['DATA_TYPE'], ['mediumtext', 'TINYTEXT', 'text', 'longtext']))
  137. {
  138. $data['rules']['text'][] = $row['COLUMN_NAME'];
  139. }
  140. if(in_array($row['DATA_TYPE'], ['bigint', 'int', 'smallint', 'tinyint', 'integer']))
  141. {
  142. preg_match('/[\d]{1,}/', $row['COLUMN_TYPE'], $matches);
  143. $data['rules']['int'][$row['COLUMN_NAME']] = $matches[0];
  144. $data['rules']['number'][] = $row['COLUMN_NAME'];
  145. }
  146. if(in_array($row['DATA_TYPE'], ['float', 'double', 'decimal']))
  147. {
  148. $data['rules']['float'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
  149. }
  150. if(in_array($row['DATA_TYPE'], ['timestamp', 'datatime']))
  151. {
  152. $data['rules']['timestamp'][] = $row['COLUMN_NAME'];
  153. }
  154. if(in_array($row['DATA_TYPE'], ['enum', 'set']))
  155. {
  156. $data['rules']['sets'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
  157. }
  158. if(isset($row['COLUMN_DEFAULT']))
  159. {
  160. $data['rules']['default'][$row['COLUMN_NAME']] = $row['COLUMN_DEFAULT'];
  161. }
  162. }
  163. $data['sql'] = $this->getTableSQL($table, $database);
  164. return $data;
  165. }
  166. /**
  167. * 从括号中获取指定的值
  168. * @param string $str 需要获取的内容
  169. * @return array
  170. */
  171. public function getValueFromBrackets($str)
  172. {
  173. preg_match("/(?:\()(.*)(?:\))/i", $str, $matches);
  174. $str = $matches[1];
  175. $a = explode(",", $str);
  176. for($i=0; $i< count($a); $i++)
  177. {
  178. $this->removeQuote($a[$i]);//从字符串中去除单引号
  179. }
  180. return $a;
  181. }
  182. /**
  183. * 去除双引号
  184. * @param string $str 去除双引号
  185. */
  186. public function removeQuote(&$str)
  187. {
  188. if(preg_match("/^\'/",$str))
  189. {
  190. $str = substr($str, 1, strlen($str)-1);
  191. }
  192. if(preg_match("/\'$/",$str))
  193. {
  194. $str = substr($str, 0, strlen($str)-1);
  195. }
  196. return $str;
  197. }
  198. /**
  199. * 查询数据库中是否有指定的表
  200. * @param string $tableName 表名
  201. * @param null|string $database 数据库
  202. * @return bool
  203. */
  204. public function hasTable($tableName, $database = null)
  205. {
  206. if($database)
  207. {
  208. $this->setQuery('USE '. $database);
  209. }
  210. $sql = "SHOW TABLES LIKE '".$tableName."'";
  211. $rs = $this->setQuery($sql);
  212. $tables = array();
  213. while($row = $this->fetch($rs))
  214. {
  215. if(is_array($row)) {
  216. foreach($row AS $val) {
  217. if($val == $tableName) return true;
  218. }
  219. }
  220. }
  221. return false;
  222. }
  223. /**
  224. * 获取创建表的SQL语句
  225. * @param string $tableName 表名
  226. * @param null|string $database 数据库
  227. * @param int|null $autoIncr 自增长的值,null的话就不使用
  228. * @return string
  229. */
  230. public function getTableSQL($tableName, $database = null, $autoIncr = null)
  231. {
  232. if($database)
  233. {
  234. $this->setQuery('USE '. $database);
  235. }
  236. $row = $this->getRow("SHOW CREATE TABLE `".$tableName."`");
  237. if(!$row) {
  238. throw new \Exception('数据表不存在', __LINE__);
  239. }
  240. $sql = $row['Create Table'];
  241. if($autoIncr === null) {
  242. return $sql;
  243. }
  244. return preg_replace("/AUTO_INCREMENT=[\d]{1,}/", "AUTO_INCREMENT=". intval($autoIncr), $sql);
  245. }
  246. /**
  247. * 通过数据表名称获取规则
  248. * @param string $table 表名
  249. * @param string $database 数据库名
  250. */
  251. public function buildRulesForTable($table, $database = null)
  252. {
  253. if(!$database) $database = $this->currentDB;
  254. $tableInfo = $this->getTableInfo($table, $database);
  255. $rules = new \Qii\Base\Rules();
  256. $rules->addFields($tableInfo['fields']);
  257. if($tableInfo['rules']['required'])
  258. {
  259. $rules->addForceValidKey($tableInfo['rules']['required']);
  260. }
  261. if(isset($tableInfo['rules']['number']))
  262. {
  263. foreach ($tableInfo['rules']['number'] as $key => $value)
  264. {
  265. $rules->addRules($value, 'number', true, $value . '字段必须是数字');
  266. }
  267. }
  268. if(isset($tableInfo['rules']['maxlength']))
  269. {
  270. foreach ($tableInfo['rules']['maxlength'] as $key => $value)
  271. {
  272. $rules->addRules($key, 'maxlength', $value, $key . '字段内容长度不能大于'. $value .'个字符');
  273. }
  274. }
  275. if(isset($tableInfo['rules']['timestamp']))
  276. {
  277. foreach ($tableInfo['rules']['timestamp'] as $key => $value)
  278. {
  279. $rules->addRules($value, 'datetime', true, $value . '字段必须为日期格式');
  280. }
  281. }
  282. return $rules;
  283. }
  284. final public function getAlias($alias)
  285. {
  286. return isset($this->_modelAlias[$alias]) ? $this->_modelAlias[$alias] : null;
  287. }
  288. /**
  289. * 设置Cache
  290. *
  291. * @param String $cache
  292. * @param Array $policy
  293. */
  294. final public function setCache($cache, $policy)
  295. {
  296. \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
  297. $this->_cache = \Qii\Autoloader\Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
  298. }
  299. /**
  300. * 缓存内容
  301. *
  302. * @param String $id
  303. * @param Array $value
  304. * @return Bool
  305. */
  306. final public function cache($id, $value)
  307. {
  308. return $this->_cache->set($id, $value);
  309. }
  310. /**
  311. * 获取缓存的类
  312. */
  313. final public function getCache()
  314. {
  315. return $this->_cache;
  316. }
  317. /**
  318. * 获取缓存内容
  319. *
  320. * @param String $id
  321. * @return Array
  322. */
  323. final public function getCacheData($id)
  324. {
  325. return $this->_cache->get($id);
  326. }
  327. /**
  328. * 获取表的名称
  329. * @param String $table
  330. * @return String
  331. */
  332. public function getTable($table)
  333. {
  334. list($database, $tableName) = array_pad(explode('.', $table), 2, '');
  335. if($tableName) return "`{$database}`.`{$tableName}`";
  336. return $table;
  337. }
  338. public function setLanguage()
  339. {
  340. $this->language = \Qii\Autoloader\Psr4::loadClass('Qii_Language_Loader');
  341. }
  342. /**
  343. *
  344. * Insert Object
  345. * @param String $table
  346. * @param Array|Object $dataArray
  347. */
  348. final function insertObject($table, $dataArray)
  349. {
  350. if (empty($table)) {
  351. return -1;
  352. }
  353. if (sizeof($dataArray) > 0 || (is_object($dataArray) && get_object_vars($dataArray)) > 0) {
  354. $keys = array();
  355. $values = array();
  356. foreach ($dataArray AS $key => $value) {
  357. $keys[] = $key;
  358. if(is_array($value))
  359. {
  360. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  361. }
  362. $values[] = $this->setQuote($value);
  363. }
  364. $this->modelSQL = $sql = "INSERT INTO ". $this->getTable($table) ."(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  365. $this->setQuery($sql);
  366. $this->cleanData();
  367. $this->setError();
  368. return $this->lastInsertId();
  369. }
  370. return -2;
  371. }
  372. /**
  373. *
  374. * Replace Object
  375. * @param String $table
  376. * @param Array|Object $dataArray
  377. */
  378. final function replaceObject($table, $dataArray)
  379. {
  380. if (empty($table)) {
  381. return -1;
  382. }
  383. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  384. $keys = array();
  385. $values = array();
  386. foreach ($dataArray AS $key => $value) {
  387. $keys[] = $key;
  388. if(is_array($value))
  389. {
  390. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  391. }
  392. $values[] = $this->setQuote($value);
  393. }
  394. $this->modelSQL = $sql = "REPLACE INTO ". $this->getTable($table) ."(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  395. $rs = $this->setQuery($sql);
  396. $this->cleanData();
  397. $this->setError();
  398. return $this->AffectedRows($rs);
  399. }
  400. return -2;
  401. }
  402. /**
  403. *
  404. * Update data
  405. * @param String $table
  406. * @param Array|Objct $dataArray
  407. * @param Array $keys
  408. */
  409. final function updateObject($table, $dataArray, $keys = array())
  410. {
  411. if (empty($table) || !is_array($keys)) {
  412. return -1;
  413. }
  414. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  415. $values = array();
  416. $where = array();
  417. foreach ($dataArray AS $key => $value) {
  418. if(is_array($value))
  419. {
  420. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  421. }
  422. $value = $this->setQuote($value);
  423. if (in_array($key, $keys)) {
  424. $where[] = "`{$key}` = '" . $value . "'";
  425. } else {
  426. $values[] = "`{$key}` = '" . $value . "'";
  427. }
  428. }
  429. //$keys为key => value的方式,就直接用keys
  430. if (empty($where) && count($keys) > 0) {
  431. foreach ($keys as $key => $value) {
  432. $value = $this->setQuote($value);
  433. $where[] = "`{$key}` = '" . $value . "'";
  434. }
  435. }
  436. $this->modelSQL = $sql = "UPDATE ". $this->getTable($table) ." SET " . join(", ", $values) . (sizeof($where) > 0 ? " WHERE " . join(" AND ", $where) : '');
  437. $rs = $this->setQuery($sql);
  438. $this->cleanData();
  439. $this->setError();
  440. return $this->AffectedRows($rs);
  441. }
  442. return 0;
  443. }
  444. /**
  445. *
  446. * 删除数据
  447. * @param String $table
  448. * @param Array $keys
  449. */
  450. final function deleteObject($table, $keys = array())
  451. {
  452. if (empty($table)) {
  453. return -1;
  454. }
  455. $where = array();
  456. if (sizeof($keys) > 0 || get_object_vars($keys)) {
  457. foreach ($keys AS $k => $v) {
  458. $where[] = "`{$k}` = '" . $this->setQuote($v) . "'";
  459. }
  460. }
  461. $this->modelSQL = $sql = "DELETE FROM ". $this->getTable($table) ." " . (sizeof($where) > 0 ? " WHERE " . join(" AND ", $where) : '');
  462. $rs = $this->query($sql);
  463. $this->cleanData();
  464. $this->setError();
  465. return $this->AffectedRows($rs);
  466. }
  467. /**
  468. * 需要清除的数据
  469. *
  470. * @return Array
  471. */
  472. final function cleanOptions()
  473. {
  474. return array('fields', 'where', 'groupBy', 'orderBy', 'limit', 'setArray');
  475. }
  476. /**
  477. * 清除数据
  478. *
  479. */
  480. final function cleanData()
  481. {
  482. $array = $this->cleanOptions();
  483. foreach ($array AS $k) {
  484. if (is_array($this->$k)) {
  485. $this->$k = array();
  486. } else {
  487. $this->$k = null;
  488. }
  489. }
  490. }
  491. /**
  492. *
  493. * 查询的字段
  494. * @param String $fileds
  495. */
  496. final function fields($fileds = "*")
  497. {
  498. $this->fields = null;
  499. if (empty($fileds)) $fileds = "*";
  500. if (is_array($fileds)) $fileds = join(',', $fileds);
  501. $this->fields = $fileds;
  502. return $this;
  503. }
  504. /**
  505. *
  506. * GROUP BY方法
  507. * @param String $fields
  508. */
  509. final function groupBy($fields)
  510. {
  511. $this->groupBy = null;
  512. if (!empty($fields)) {
  513. $this->groupBy = sprintf($this->_query['GROUP'], $fields);
  514. }
  515. return $this;
  516. }
  517. /**
  518. *
  519. * 插入数据用
  520. * @param Array $array
  521. */
  522. final function dataArray($array)
  523. {
  524. $this->fileds = null;
  525. if (is_array($array)) {
  526. $tmpArray = array();
  527. foreach ($array AS $k => $v) {
  528. $tmpArray['k'][] = $k;
  529. $tmpArray['v'][] = $this->setQuote($v);
  530. }
  531. $this->fileds = $tmpArray;
  532. }
  533. return $this;
  534. }
  535. /**
  536. *
  537. * Order By函数
  538. * @param String $field
  539. * @param String $orderBy
  540. */
  541. final function orderBy($field, $orderBy)
  542. {
  543. if(!empty($field)) return $this;
  544. if($this->orderBy != '') {
  545. $this->orderBy .= $field .' '. $orderBy;
  546. }else{
  547. $this->orderBy = sprintf($this->_query['ORDER'], $field, $orderBy);
  548. }
  549. }
  550. final function orderByArr($map)
  551. {
  552. if(empty($map)) return $this;
  553. foreach($map AS $val)
  554. {
  555. $this->orderBy($val['field'], $val['orderBy']);
  556. }
  557. return $this;
  558. }
  559. final function orderByStr($orderBy)
  560. {
  561. if(!$orderBy) return $this;
  562. $this->orderBy = $orderBy;
  563. return $this;
  564. }
  565. /**
  566. *
  567. * Limit函数,如果省略第二个参数则第一个为0,第二个参数值取第一个
  568. * @param Int $limit
  569. * @param Int $offset
  570. */
  571. final function limit($limit, $offset = 0)
  572. {
  573. $this->limit = null;
  574. if ($limit !== '') {
  575. if (!$offset) {
  576. $this->limit = sprintf($this->_query["LIMIT"], 0, $limit);
  577. } else {
  578. $this->limit = sprintf($this->_query["LIMIT"], $limit, $offset);
  579. }
  580. }
  581. return $this;
  582. }
  583. final function like($like)
  584. {
  585. if(empty($like)) return $this;
  586. $likeArray = array();
  587. if($like && !is_array($like))
  588. {
  589. $likeArray[] = $like;
  590. }
  591. else
  592. {
  593. foreach($like AS $key => $val)
  594. {
  595. $likeArray[] = sprintf($this->_query['LIKE'], $key, "%". $this->setQuote($val) . "%");
  596. }
  597. }
  598. if(count($likeArray) > 0)
  599. {
  600. $likeSQL = join(" OR ", $likeArray);
  601. echo $likeSQL;
  602. $this->where = sprintf($this->_query["WHERE"], $likeSQL);
  603. }
  604. return $this;
  605. }
  606. /**
  607. * 传的条件为数组
  608. * @param Array $where 条件
  609. * @return Object 对象本身
  610. */
  611. final function whereArray($where)
  612. {
  613. $this->where = null;
  614. if (!empty($where)) {
  615. $whereArray = array();
  616. foreach ($where AS $k => $v) {
  617. $whereArray[] = " `{$k}` = '{$v}'";
  618. }
  619. if (sizeof($whereArray) > 0) {
  620. $whereSQL = join(" AND ", $whereArray);
  621. $this->where = sprintf($this->_query["WHERE"], $whereSQL);
  622. }
  623. }
  624. return $this;
  625. }
  626. /**
  627. *
  628. * WHERE 子句
  629. * @param String $where
  630. */
  631. final function where($where)
  632. {
  633. if (is_array($where)) return $this->whereArray($where);
  634. $this->where = null;
  635. if (!empty($where)) {
  636. $this->where = sprintf($this->_query["WHERE"], $where);
  637. }
  638. return $this;
  639. }
  640. /**
  641. *
  642. * 插入数据到指定表中
  643. * @param String $table
  644. */
  645. final function insertRow($table)
  646. {
  647. $this->modelSQL = $sql = sprintf($this->_query['INSERT'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  648. $this->cleanData();
  649. $this->setQuery($sql, '');
  650. return $this->lastInsertId();
  651. }
  652. /**
  653. *
  654. * Replace方法
  655. * @param String $table
  656. */
  657. final function replaceRow($table)
  658. {
  659. $this->modelSQL = $sql = sprintf($this->_query['REPLACE'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  660. $this->cleanData();
  661. return $this->exec($sql);
  662. }
  663. /**
  664. *
  665. * 查询一行
  666. * @param String $table
  667. */
  668. final function selectRow($table)
  669. {
  670. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  671. $this->cleanData();
  672. return $this->getRow($sql);
  673. }
  674. /**
  675. *
  676. * 查询一行
  677. * @param String $table
  678. */
  679. final function selectOne($table)
  680. {
  681. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  682. $this->cleanData();
  683. return $this->getOne($sql);
  684. }
  685. /**
  686. * 创建SQL
  687. */
  688. final function createSQL($table)
  689. {
  690. $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  691. $this->cleanData();
  692. return $sql;
  693. }
  694. /**
  695. *
  696. * 查询所有
  697. * @param String $table 数据表名称
  698. * @return Array
  699. */
  700. final function selectAll($table)
  701. {
  702. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  703. $this->cleanData();
  704. return $this->getAll($sql);
  705. }
  706. /**
  707. * 返回resource资源
  708. * @param string $table 数据表名称
  709. */
  710. final function rs($table)
  711. {
  712. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  713. $this->cleanData();
  714. return $this->setQuery($sql);
  715. }
  716. /**
  717. * 将指定字段减指定值
  718. *
  719. * @param array $data 数据
  720. * @return $this
  721. */
  722. final function downsetCounter($data)
  723. {
  724. if (is_array($data)) {
  725. foreach ($data AS $k => $value) {
  726. $this->setArray[] = $k . "=" . $k . '-' . $value;
  727. }
  728. }
  729. $this->set(null);
  730. return $this;
  731. }
  732. /**
  733. * 将指定字段加指定值
  734. *
  735. * @param $data
  736. * @return $this
  737. */
  738. final function upsetCounter($data)
  739. {
  740. if (is_array($data)) {
  741. foreach ($data AS $k => $value) {
  742. $this->setArray[] = $k . "=" . $k . '+' . $value;
  743. }
  744. }
  745. $this->set(null);
  746. return $this;
  747. }
  748. /**
  749. * 更新数据时候用,方法同setData
  750. * @param Array $data
  751. */
  752. final function set($data)
  753. {
  754. return $this->setData($data);
  755. }
  756. /**
  757. *
  758. * 更新数据时候用
  759. * @param Array $data
  760. * @return $this
  761. */
  762. final function setData($data)
  763. {
  764. if (is_array($data)) {
  765. $set = array();
  766. foreach ($data AS $k => $value) {
  767. $set[] = $k . "='" . $this->setQuote($value) . "'";
  768. }
  769. if (sizeof($this->setArray) > 0) {
  770. $this->set = " " . join(", ", $set) . ", " . join(",", $this->setArray);
  771. } else {
  772. $this->set = " " . join(", ", $set);
  773. }
  774. } else {
  775. if (sizeof($this->setArray) > 0) {
  776. $this->set = join(",", $this->setArray);
  777. } else {
  778. $this->set = "";
  779. }
  780. }
  781. return $this;
  782. }
  783. /**
  784. * 执行更新操作,updateRows的alias
  785. * @param String $table
  786. * @return number
  787. */
  788. /*
  789. final function update($table){
  790. return $this->updateRows($table);
  791. }
  792. */
  793. /**
  794. *
  795. * 执行更新操作
  796. * @param $table
  797. * @return Int 返回影响的行数
  798. */
  799. final function updateRows($table)
  800. {
  801. $this->modelSQL = $sql = sprintf($this->_query['UPDATE'], $table) . $this->set . $this->where . $this->limit;
  802. $this->cleanData();
  803. return $this->exec($sql);
  804. }
  805. /**
  806. *
  807. * 执行删除操作
  808. * @param String $table
  809. */
  810. final function deleteRows($table)
  811. {
  812. $this->modelSQL = $sql = sprintf($this->_query['DELETE'], $table, $this->where) . $this->limit;
  813. $this->cleanData();
  814. return $this->exec($sql);
  815. }
  816. /**
  817. * 执行Model过程中保存的相关信息
  818. *
  819. * @param String $option
  820. * @return Mix
  821. */
  822. final function querySQL($option = '')
  823. {
  824. $allow = array('_queryTimes', '_querySeconds', '_errorInfo', '_exeSQL');
  825. if (in_array($option, $allow)) {
  826. return $this->{$option};
  827. }
  828. return 0;
  829. }
  830. /**
  831. * 将结果编码一下
  832. * @param String $word
  833. * @return String|multitype:
  834. */
  835. public function setQuote($word)//过滤sql字符
  836. {
  837. if (ini_get("magic_quotes_gpc")) {
  838. return $word;
  839. }
  840. return is_array($word) ? array_map('addslashes', $word) : addslashes($word);
  841. }
  842. /**
  843. * 获取错误码
  844. */
  845. public function getCode()
  846. {
  847. return $this->_response->getCode();
  848. }
  849. /**
  850. * 获取错误信息
  851. */
  852. public function getMessage()
  853. {
  854. if($this->_response->isError())
  855. {
  856. return $this->_response->getMessage();
  857. }
  858. }
  859. /**
  860. * 返回response对象
  861. *
  862. * @return Bool
  863. */
  864. public function getResponse()
  865. {
  866. return $this->_response;
  867. }
  868. public function iconv($str)
  869. {
  870. if (is_array($str)) {
  871. return array_map(function ($n) {
  872. return iconv('GB2312', 'UTF-8', $n);
  873. }, $str);
  874. }
  875. return iconv('GB2312', 'UTF-8', $str);
  876. }
  877. /**
  878. * 如果不存在指定的方法则调用提示错误
  879. *
  880. * @param String $name
  881. * @param Mix $args
  882. * @return Mix
  883. */
  884. public function __call($method, $argvs)
  885. {
  886. if (isset($this->_modelAlias[$method])) {
  887. if (method_exists($this, $this->_modelAlias[$method])) {
  888. return call_user_func_array(array($this, $this->_modelAlias[$method]), $argvs);
  889. }
  890. \Qii::setError(false, __LINE__, 1506, 'Alias ' . get_called_class() . '->' . $method . '()');
  891. }
  892. \Qii::setError(false, __LINE__, 1506, get_called_class() . '->' . $method . '()');
  893. }
  894. }