dao.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  1. <?php
  2. /**
  3. * mysql dao 工具类: 目的是提高写sql语句的效率,但是应该是涉及到sql开发的地方不会太多...
  4. * ver: 2017.05.25 由王刚导入并调试, 慢慢发展, 不着急推广.
  5. * Ps.至于可用性和稳定性还差的远, 直接执行sql语句是最靠谱的方式.
  6. * 用法备注:
  7. * select 用法: 最后必须得有fetch/fetchall/fetchPairs/fetchGroup...
  8. * $dao->select()->from('table') // 必选
  9. * ->where()->eq()/gt()/lt() // 可选
  10. * ->andwhere()->in() // 可选
  11. * ->orderby() // 可选
  12. * ->limit() // 可选
  13. * ->fetch*(); // 必选
  14. * insert 用法: 最后必须得有exec()
  15. * $dao->insert('table') // 必选
  16. * ->data(data) // 必选 data 为['filed'=>value,...]或{'k':v,...}
  17. * ->*check() // 可选
  18. * ->exec() // 必选
  19. * 或 $dao->insert('table')
  20. * ->set('filed')->eq(value)
  21. * ->set()->eq()...
  22. * ->exec()
  23. * update 用法: 必须得有data(),where()和exec()
  24. * $dao->update('table') // 必选
  25. * ->data(change) // 必选 change 为['filed'=>value,...]或{'k':v,...}
  26. * ->*check() // 可选
  27. * ->where()->eq/lt/gt() // 必选
  28. * ->andwhere()->eq/lt/gt() // 可选
  29. * ->exec() // 必选
  30. * 或 * $dao->update('table') // 必选
  31. * ->set('field')->eq(value) // 必选
  32. * ->set()->eq()... // 可选
  33. * ->*check() // 可选
  34. * ->where()->eq/lt/gt() // 必选
  35. * ->andwhere()->eq/lt/gt() // 可选
  36. * ->exec() // 必选
  37. * delete 用法: 必须得有exec
  38. * $dao->delete()->from('table') // 必选
  39. * ->where('field')->eq/lt/gt(value) // 必选
  40. * ->andwhere()->eq/gt/lt()... // 可选
  41. * ->exec() // 必选
  42. * 更多用法继续参考禅道项目中具体代码(本人(gwang)参考的7.0版本).
  43. * (http://dl.cnezsoft.com/zentao/7.0/ZenTaoPMS.7.0.stable.zip)
  44. *
  45. */
  46. /**
  47. * The dao and sql class file of ZenTaoPHP framework.
  48. *
  49. * The author disclaims copyright to this source code. In place of
  50. * a legal notice, here is a blessing:
  51. *
  52. * May you do good and not evil.
  53. * May you find forgiveness for yourself and forgive others.
  54. * May you share freely, never taking more than you give.
  55. */
  56. namespace loyalsoft;
  57. use \PDO;
  58. use \PDOException;
  59. /**
  60. * DAO, data access object.
  61. *
  62. * @package framework
  63. */
  64. class dao {
  65. /* Use these strang strings to avoid conflicting with these keywords in the sql body. */
  66. const WHERE = 'wHeRe';
  67. const GROUPBY = 'gRoUp bY';
  68. const HAVING = 'hAvInG';
  69. const ORDERBY = 'oRdEr bY';
  70. const LIMIT = 'lImiT';
  71. /**
  72. * The global dbh(database handler) object.
  73. *
  74. * @var object
  75. * @access protected
  76. */
  77. protected $dbh;
  78. /**
  79. * The global slaveDBH(database handler) object.
  80. * 从数据库, 主从架构, 主库写如, 从库查询
  81. * @var object
  82. * @access protected
  83. */
  84. protected $slaveDBH;
  85. /**
  86. * The sql object, used to creat the query sql.
  87. *
  88. * @var object
  89. * @access protected
  90. */
  91. public $sqlobj;
  92. /**
  93. * The table of current query.
  94. *
  95. * @var string
  96. * @access public
  97. */
  98. public $table;
  99. /**
  100. * The alias of $this->table.
  101. *
  102. * @var string
  103. * @access public
  104. */
  105. public $alias;
  106. /**
  107. * The fields will be returned.
  108. *
  109. * @var string
  110. * @access public
  111. */
  112. public $fields;
  113. /**
  114. * The query mode, raw or magic.
  115. *
  116. * This var is used to diff dao::from() with sql::from().
  117. *
  118. * @var string
  119. * @access public
  120. */
  121. public $mode;
  122. /**
  123. * The query method: insert, select, update, delete, replace.
  124. *
  125. * @var string
  126. * @access public
  127. */
  128. public $method;
  129. /**
  130. * The sql code of need repair table.
  131. *
  132. * @var string
  133. * @access public
  134. */
  135. public $repairCode = '|1034|1035|1194|1195|1459|';
  136. /**
  137. * The queries executed. Every query will be saved in this array.
  138. *
  139. * @var array
  140. * @access public
  141. */
  142. static public $querys = array();
  143. /**
  144. * The errors.
  145. *
  146. * @var array
  147. * @access public
  148. */
  149. static public $errors = array();
  150. /**
  151. * The construct method.
  152. *
  153. * @access public
  154. * @return void
  155. */
  156. public function __construct() {
  157. }
  158. /**
  159. * Connect to database.
  160. * @param assoc_array $config 配置
  161. * @access public
  162. * @return void
  163. */
  164. public function connectDB($config) {
  165. global $dbh, $slaveDBH;
  166. if (isset($config->paydb->host)) {
  167. $this->dbh = $dbh = $this->connectByPDO($config->paydb);
  168. }
  169. if (isset($config->slaveDB->host)) {
  170. $this->slaveDBH = $slaveDBH = $this->connectByPDO($config->slaveDB);
  171. }
  172. }
  173. /**
  174. * Connect database by PDO.
  175. *
  176. * @param object $params the database params.
  177. * @access private
  178. * @return object|bool
  179. */
  180. private function connectByPDO($params) {
  181. if (!isset($params->driver)) {
  182. self::triggerError('no pdo driver defined, it should be mysql or sqlite', __FILE__, __LINE__, $exit = true);
  183. }
  184. if (!isset($params->user)) {
  185. return false;
  186. }
  187. if ($params->driver == 'mysql') {
  188. $dsn = "mysql:host={$params->host}; port={$params->port}; dbname={$params->name}";
  189. }
  190. try {
  191. $dbh = new \PDO($dsn, $params->user, $params->password, array(PDO::ATTR_PERSISTENT => $params->persistant));
  192. $dbh->exec("SET NAMES {$params->encoding}");
  193. /* If run on linux, set emulatePrepare and bufferQuery to true. */
  194. if (!isset($params->emulatePrepare) and PHP_OS == 'Linux') {
  195. $params->emulatePrepare = true;
  196. }
  197. if (!isset($params->bufferQuery) and PHP_OS == 'Linux') {
  198. $params->bufferQuery = true;
  199. }
  200. $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
  201. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  202. if (isset($params->strictMode) and $params->strictMode == false) {
  203. $dbh->exec("SET @@sql_mode= ''");
  204. }
  205. if (isset($params->emulatePrepare)) {
  206. $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, $params->emulatePrepare);
  207. }
  208. if (isset($params->bufferQuery)) {
  209. $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $params->bufferQuery);
  210. }
  211. return $dbh;
  212. } catch (PDOException $exception) {
  213. self::triggerError($exception->getMessage(), __FILE__, __LINE__, $exit = true);
  214. }
  215. }
  216. /**
  217. * Set the $table property.
  218. *
  219. * @param string $table
  220. * @access private
  221. * @return void
  222. */
  223. private function setTable($table) {
  224. $this->table = $table;
  225. }
  226. /**
  227. * Set the $alias property.
  228. *
  229. * @param string $alias
  230. * @access private
  231. * @return void
  232. */
  233. private function setAlias($alias) {
  234. $this->alias = $alias;
  235. }
  236. /**
  237. * Set the $fields property.
  238. *
  239. * @param string $fields
  240. * @access private
  241. * @return void
  242. */
  243. private function setFields($fields) {
  244. $this->fields = $fields;
  245. }
  246. /**
  247. * Reset the vars.
  248. *
  249. * @access private
  250. * @return void
  251. */
  252. private function reset() {
  253. $this->setFields('');
  254. $this->setTable('');
  255. $this->setAlias('');
  256. $this->setMode('');
  257. $this->setMethod('');
  258. }
  259. //-------------------- According to the query method, call according method of sql class. --------------------//
  260. /**
  261. * Set the query mode. If the method if like findByxxx, the mode is magic. Else, the mode is raw.
  262. *
  263. * @param string $mode magic|raw
  264. * @access private
  265. * @return void
  266. */
  267. private function setMode($mode = '') {
  268. $this->mode = $mode;
  269. }
  270. /**
  271. * Set the query method: select|update|insert|delete|replace
  272. *
  273. * @param string $method
  274. * @access private
  275. * @return void
  276. */
  277. private function setMethod($method = '') {
  278. $this->method = $method;
  279. }
  280. /**
  281. * The select method, call sql::select().
  282. *
  283. * @param string $fields
  284. * @access public
  285. * @return object the dao object self.
  286. */
  287. public function select($fields = '*') {
  288. $this->setMode('raw');
  289. $this->setMethod('select');
  290. $this->sqlobj = sql::select($fields);
  291. return $this;
  292. }
  293. /**
  294. * The count method, call sql::select() and from().
  295. * use as $this->dao->select()->from(TABLE_BUG)->where()->count();
  296. *
  297. * @access public
  298. * @return void
  299. */
  300. public function count() {
  301. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  302. // $this->fields
  303. $sql = $this->processSQL();
  304. $sql = str_replace('SELECT', 'SELECT SQL_CALC_FOUND_ROWS ', $sql);
  305. /* Remove the part after order and limit. */
  306. $subLength = strlen($sql);
  307. $orderPOS = strripos($sql, DAO::ORDERBY);
  308. $limitPOS = strripos($sql, DAO::LIMIT);
  309. if ($limitPOS) {
  310. $subLength = $limitPOS;
  311. }
  312. if ($orderPOS) {
  313. $subLength = $orderPOS;
  314. }
  315. $sql = substr($sql, 0, $subLength);
  316. self::$querys[] = $sql;
  317. /* Get the records count. */
  318. try {
  319. $row = $this->dbh->query($sql)->fetch(PDO::FETCH_OBJ);
  320. } catch (\PDOException $e) {
  321. $this->sqlError($e);
  322. }
  323. // CLogUtil_HP::paylog($sql);
  324. // var_dump($row);
  325. $sql = 'SELECT FOUND_ROWS() as recTotal;';
  326. $row = $this->dbh->query($sql)->fetch();
  327. return $row->recTotal;
  328. }
  329. /**
  330. * The select method, call sql::update().
  331. *
  332. * @param string $table
  333. * @access public
  334. * @return object the dao object self.
  335. */
  336. public function update($table) {
  337. $this->setMode('raw');
  338. $this->setMethod('update');
  339. $this->sqlobj = sql::update($table);
  340. $this->setTable($table);
  341. return $this;
  342. }
  343. /**
  344. * The delete method, call sql::delete().
  345. *
  346. * @access public
  347. * @return object the dao object self.
  348. */
  349. public function delete() {
  350. $this->setMode('raw');
  351. $this->setMethod('delete');
  352. $this->sqlobj = sql::delete();
  353. return $this;
  354. }
  355. /**
  356. * The insert method, call sql::insert().
  357. *
  358. * @param string $table
  359. * @access public
  360. * @return object the dao object self.
  361. */
  362. public function insert($table) {
  363. $this->setMode('raw');
  364. $this->setMethod('insert');
  365. $this->sqlobj = sql::insert($table);
  366. $this->setTable($table);
  367. return $this;
  368. }
  369. /**
  370. * The insert method, call sql::insert().
  371. *
  372. * @param string $table
  373. * @access public
  374. * @return object the dao object self.
  375. */
  376. public function del($table) {
  377. $this->setMode('raw');
  378. $this->setMethod('DELETE');
  379. $this->sqlobj = sql::del($table);
  380. $this->setTable($table);
  381. return $this;
  382. }
  383. /**
  384. * The replace method, call sql::replace().
  385. *
  386. * @param string $table
  387. * @access public
  388. * @return object the dao object self.
  389. */
  390. public function replace($table) {
  391. $this->setMode('raw');
  392. $this->setMethod('replace');
  393. $this->sqlobj = sql::replace($table);
  394. $this->setTable($table);
  395. return $this;
  396. }
  397. /**
  398. * Set the from table.
  399. *
  400. * @param string $table
  401. * @access public
  402. * @return object the dao object self.
  403. */
  404. public function from($table) {
  405. $this->setTable($table);
  406. if ($this->mode == 'raw') {
  407. $this->sqlobj->from($table);
  408. }
  409. return $this;
  410. }
  411. /**
  412. * Set the fields.
  413. *
  414. * @param string $fields
  415. * @access public
  416. * @return object the dao object self.
  417. */
  418. public function fields($fields) {
  419. $this->setFields($fields);
  420. return $this;
  421. }
  422. /**
  423. * Alias a table, equal the AS keyword. (Don't use AS, because it's a php keyword.)
  424. *
  425. * @param string $alias
  426. * @access public
  427. * @return object the dao object self.
  428. */
  429. public function alias($alias) {
  430. if (empty($this->alias)) {
  431. $this->setAlias($alias);
  432. }
  433. $this->sqlobj->alias($alias);
  434. return $this;
  435. }
  436. /**
  437. * Set the data to update or insert.(注意: 只能支持单条数据的插入或者更新 -王刚)
  438. *
  439. * @param object $data the data object or array
  440. * @access public
  441. * @return object the dao object self.
  442. */
  443. public function data($data) {
  444. if (!is_object($data)) {
  445. $data = (object) $data;
  446. }
  447. $this->sqlobj->data($data);
  448. return $this;
  449. }
  450. //-------------------- The sql related method. --------------------//
  451. /**
  452. * Get the sql string.
  453. *
  454. * @access public
  455. * @return string the sql string after process.
  456. */
  457. public function get() {
  458. return $this->processKeywords($this->processSQL());
  459. }
  460. /**
  461. * Print the sql string.
  462. *
  463. * @access public
  464. * @return void
  465. */
  466. public function printSQL() {
  467. echo $this->processSQL();
  468. }
  469. /**
  470. * Process the sql, replace the table, fields.
  471. *
  472. * @access private
  473. * @return string the sql string after process.
  474. */
  475. private function processSQL() {
  476. $sql = $this->sqlobj->get();
  477. /* If the mode is magic, process the $fields and $table. */
  478. if ($this->mode == 'magic') {
  479. if ($this->fields == '') {
  480. $this->fields = '*';
  481. }
  482. if ($this->table == '') {
  483. $this->triggerError('Must set the table name', __FILE__, __LINE__, $exit = true);
  484. }
  485. $sql = sprintf($this->sqlobj->get(), $this->fields, $this->table);
  486. }
  487. self::$querys[] = $this->processKeywords($sql);
  488. return $sql;
  489. }
  490. /**
  491. * Trriger an error.
  492. *
  493. * @param string $message error message
  494. * @param string $file the file error occers
  495. * @param int $line the line error occers
  496. * @param bool $exit exit the program or not
  497. * @access public
  498. * @return void
  499. */
  500. private function triggerError($message, $file, $line, $exit = false) {
  501. /* Set the error info. */
  502. $log = "ERROR: " . CommUtil::str2UTF8($message) . " in " . CommUtil::str2UTF8($file) . " on line $line";
  503. if (isset($_SERVER['SCRIPT_URI'])) {
  504. $log .= ", request: $_SERVER[SCRIPT_URI]";
  505. }
  506. $trace = debug_backtrace();
  507. extract($trace[0]); # function
  508. extract($trace[1]); # line
  509. $log .= ", last called by $file on line $line through function $function.\n";
  510. CLog::err($log, "dao");
  511. CLog::err($trace, "dao");
  512. /* Trigger it. */
  513. trigger_error($log, $exit ? E_USER_ERROR : E_USER_WARNING);
  514. }
  515. /**
  516. * Process the sql keywords, replace the constants to normal.
  517. *
  518. * @param string $sql
  519. * @access private
  520. * @return string the sql string.
  521. */
  522. private function processKeywords($sql) {
  523. return str_replace(array(DAO::WHERE, DAO::GROUPBY, DAO::HAVING, DAO::ORDERBY, DAO::LIMIT), array('WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT'), $sql);
  524. }
  525. //-------------------- Query related methods. --------------------//
  526. /**
  527. * Set the dbh.
  528. *
  529. * You can use like this: $this->dao->dbh($dbh), thus you can handle two database.
  530. *
  531. * @param object $dbh
  532. * @access public
  533. * @return object the dao object self.
  534. */
  535. public function dbh($dbh) {
  536. $this->dbh = $dbh;
  537. return $this;
  538. }
  539. /**
  540. * Query the sql, return the statement object.
  541. *
  542. * @param string $sql
  543. * @access public
  544. * @return object the PDOStatement object.
  545. */
  546. public function query($sql = '') {
  547. if (!empty(dao::$errors)) {
  548. return new PDOStatement(); // If any error, return an empty statement object to make sure the remain method to execute.
  549. }
  550. if ($sql) {
  551. if (is_null($this->sqlobj)) {
  552. $this->sqlobj = sql::factory();
  553. }
  554. $this->sqlobj->sql = $sql;
  555. }
  556. $sql = $this->processSQL();
  557. try {
  558. $method = $this->method;
  559. $this->reset();
  560. // var_dump($sql);
  561. if ($this->slaveDBH and $method == 'select') {
  562. return $this->slaveDBH->query($sql);
  563. } else {
  564. return $this->dbh->query($sql);
  565. }
  566. } catch (\PDOException $e) {
  567. $this->sqlError($e);
  568. }
  569. }
  570. /**
  571. * Page the records, set the limit part auto.
  572. *
  573. * @param object $pager
  574. * @access public
  575. * @return object the dao object self.
  576. */
  577. public function page($pager) {
  578. if (!is_object($pager)) {
  579. return $this;
  580. }
  581. /* If the record total is 0, compute it. */
  582. if ($pager->recTotal == 0) {
  583. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  584. $sql = $this->get();
  585. $selectPOS = strpos($sql, 'SELECT') + strlen('SELECT');
  586. $fromPOS = strpos($sql, 'FROM');
  587. $fields = substr($sql, $selectPOS, $fromPOS - $selectPOS);
  588. $sql = str_replace($fields, ' COUNT(*) AS recTotal ', $sql);
  589. /* Remove the part after order and limit. */
  590. $subLength = strlen($sql);
  591. $orderPOS = strripos($sql, 'order ');
  592. $limitPOS = strripos($sql, 'limit');
  593. if ($limitPOS) {
  594. $subLength = $limitPOS;
  595. }
  596. if ($orderPOS) {
  597. $subLength = $orderPOS;
  598. }
  599. $sql = substr($sql, 0, $subLength);
  600. self::$querys[] = $sql;
  601. /* Get the records count. */
  602. try {
  603. $row = $this->dbh->query($sql)->fetch(PDO::FETCH_OBJ);
  604. } catch (\PDOException $e) {
  605. $this->sqlError($e);
  606. }
  607. $pager->setRecTotal($row->recTotal);
  608. $pager->setPageTotal();
  609. }
  610. $this->sqlobj->limit($pager->limit());
  611. return $this;
  612. }
  613. /**
  614. * 字符串引号处理
  615. * @param type $str
  616. * @param type $parameter_type
  617. * @return type
  618. */
  619. public function quote($str, $parameter_type = PDO::PARAM_STR) {
  620. return $this->dbh->quote($str, $parameter_type);
  621. }
  622. /**
  623. * Execute the sql. It's different with query(), which return the stmt object. But this not.
  624. *
  625. * @param string $sql
  626. * @access public
  627. * @return int the modified or deleted records.
  628. */
  629. public function exec($sql = '') {
  630. if (!empty(dao::$errors)) {
  631. return new PDOStatement(); // If any error, return an empty statement object to make sure the remain method to execute.
  632. }
  633. if ($sql) {
  634. if (is_null($this->sqlobj)) {
  635. $this->sqlobj = sql::factory();
  636. }
  637. $this->sqlobj->sql = $sql;
  638. }
  639. $sql = $this->processSQL();
  640. // var_dump($sql);
  641. try {
  642. $this->reset();
  643. return $this->dbh->exec($sql);
  644. } catch (\PDOException $e) {
  645. $this->sqlError($e);
  646. }
  647. }
  648. //-------------------- Fetch related methods. -------------------//
  649. /**
  650. * Fetch one record.
  651. *
  652. * @param string $field if the field is set, only return the value of this field, else return this record
  653. * @access public
  654. * @return object|mixed
  655. */
  656. public function fetch($field = '') {
  657. if (empty($field)) {
  658. return $this->query()->fetch();
  659. }
  660. $this->setFields($field);
  661. $result = $this->query()->fetch(PDO::FETCH_OBJ);
  662. if ($result) {
  663. return $result->$field;
  664. }
  665. return false;
  666. }
  667. /**
  668. * Fetch all records.
  669. *
  670. * @param string $keyField the key field, thus the return records is keyed by this field
  671. * @access public
  672. * @return array the records
  673. */
  674. public function fetchAll($keyField = '') {
  675. $stmt = $this->query();
  676. if (empty($keyField)) {
  677. return $stmt->fetchAll();
  678. }
  679. $rows = array();
  680. while ($row = $stmt->fetch()) {
  681. $rows[$row->$keyField] = $row;
  682. }
  683. return $rows;
  684. }
  685. /**
  686. * Fetch all records and group them by one field.
  687. *
  688. * @param string $groupField the field to group by
  689. * @param string $keyField the field of key
  690. * @access public
  691. * @return array the records.
  692. */
  693. public function fetchGroup($groupField, $keyField = '') {
  694. $stmt = $this->query();
  695. $rows = array();
  696. while ($row = $stmt->fetch()) {
  697. empty($keyField) ? $rows[$row->$groupField][] = $row : $rows[$row->$groupField][$row->$keyField] = $row;
  698. }
  699. return $rows;
  700. }
  701. /**
  702. * Fetch array like key=>value.
  703. *
  704. * If the keyFiled and valueField not set, use the first and last in the record.
  705. *
  706. * @param string $keyField
  707. * @param string $valueField
  708. * @access public
  709. * @return array
  710. */
  711. public function fetchPairs($keyField = '', $valueField = '') {
  712. $pairs = array();
  713. $ready = false;
  714. $stmt = $this->query();
  715. while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  716. if (!$ready) {
  717. if (empty($keyField)) {
  718. $keyField = key($row);
  719. }
  720. if (empty($valueField)) {
  721. end($row);
  722. $valueField = key($row);
  723. }
  724. $ready = true;
  725. }
  726. $pairs[$row[$keyField]] = $row[$valueField];
  727. }
  728. return $pairs;
  729. }
  730. /**
  731. * Return the last insert ID.
  732. *
  733. * @access public
  734. * @return int
  735. */
  736. public function lastInsertID() {
  737. return $this->dbh->lastInsertID();
  738. }
  739. //-------------------- Magic methods.--------------------//
  740. /**
  741. * Use it to do some convenient queries.
  742. *
  743. * @param string $funcName the function name to be called
  744. * @param array $funcArgs the params
  745. * @access public
  746. * @return object the dao object self.
  747. */
  748. public function __call($funcName, $funcArgs) {
  749. $funcName = strtolower($funcName);
  750. /* findByxxx, xxx as will be in the where. */
  751. if (strpos($funcName, 'findby') !== false) {
  752. $this->setMode('magic');
  753. $field = str_replace('findby', '', $funcName);
  754. if (count($funcArgs) == 1) {
  755. $operator = '=';
  756. $value = $funcArgs[0];
  757. } else {
  758. $operator = $funcArgs[0];
  759. $value = $funcArgs[1];
  760. }
  761. $this->sqlobj = sql::select('%s')->from('%s')->where($field, $operator, $value);
  762. return $this;
  763. }
  764. /* Fetch10. */ elseif (strpos($funcName, 'fetch') !== false) {
  765. $max = str_replace('fetch', '', $funcName);
  766. $stmt = $this->query();
  767. $rows = array();
  768. $key = isset($funcArgs[0]) ? $funcArgs[0] : '';
  769. $i = 0;
  770. while ($row = $stmt->fetch()) {
  771. $key ? $rows[$row->$key] = $row : $rows[] = $row;
  772. $i++;
  773. if ($i == $max) {
  774. break;
  775. }
  776. }
  777. return $rows;
  778. }
  779. /* Others, call the method in sql class. */ else {
  780. /* Create the max counts of sql class methods, and then create $arg0, $arg1... */
  781. for ($i = 0; $i < SQL::MAX_ARGS; $i++) {
  782. ${"arg$i"} = isset($funcArgs[$i]) ? $funcArgs[$i] : null;
  783. }
  784. $this->sqlobj->$funcName($arg0, $arg1, $arg2);
  785. return $this;
  786. }
  787. }
  788. //-------------------- Checking.--------------------//
  789. /**
  790. * Check a filed is satisfied with the check rule.
  791. *
  792. * @param string $fieldName the field to check
  793. * @param string $funcName the check rule
  794. * @access public
  795. * @return object the dao object self.
  796. */
  797. public function check($fieldName, $funcName) {
  798. /* If no this field in the data, reuturn. */
  799. if (!isset($this->sqlobj->data->$fieldName)) {
  800. return $this;
  801. }
  802. /* Set the field label and value. */
  803. global $lang, $config, $app;
  804. $table = strtolower(str_replace(array($config->db->prefix, '`'), '', $this->table));
  805. $fieldLabel = isset($lang->$table->$fieldName) ? $lang->$table->$fieldName : $fieldName;
  806. $value = $this->sqlobj->data->$fieldName;
  807. /* Check unique. */
  808. if ($funcName == 'unique') {
  809. $args = func_get_args();
  810. $sql = "SELECT COUNT(*) AS count FROM $this->table WHERE `$fieldName` = " . $this->sqlobj->quote($value);
  811. if (isset($args[2])) {
  812. $sql .= ' AND ' . $args[2];
  813. }
  814. try {
  815. $row = $this->dbh->query($sql)->fetch();
  816. if ($row->count != 0) {
  817. $this->logError($funcName, $fieldName, $fieldLabel, array($value));
  818. }
  819. } catch (PDOException $e) {
  820. $this->sqlError($e);
  821. }
  822. } else {
  823. /* Create the params. */
  824. $funcArgs = func_get_args();
  825. unset($funcArgs[0]);
  826. unset($funcArgs[1]);
  827. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  828. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  829. }
  830. $checkFunc = 'check' . $funcName;
  831. if (validater::$checkFunc($value, $arg0, $arg1, $arg2) === false) {
  832. $this->logError($funcName, $fieldName, $fieldLabel, $funcArgs);
  833. }
  834. }
  835. return $this;
  836. }
  837. /**
  838. * Check a field, if satisfied with the condition.
  839. *
  840. * @param string $condition
  841. * @param string $fieldName
  842. * @param string $funcName
  843. * @access public
  844. * @return object the dao object self.
  845. */
  846. public function checkIF($condition, $fieldName, $funcName) {
  847. if (!$condition) {
  848. return $this;
  849. }
  850. $funcArgs = func_get_args();
  851. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  852. ${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
  853. }
  854. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  855. return $this;
  856. }
  857. /**
  858. * Batch check some fileds.
  859. *
  860. * @param string $fields the fields to check, join with ,
  861. * @param string $funcName
  862. * @access public
  863. * @return object the dao object self.
  864. */
  865. public function batchCheck($fields, $funcName) {
  866. $fields = explode(',', str_replace(' ', '', $fields));
  867. $funcArgs = func_get_args();
  868. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  869. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  870. }
  871. foreach ($fields as $fieldName) {
  872. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  873. }
  874. return $this;
  875. }
  876. /**
  877. * Batch check fields on the condition is true.
  878. *
  879. * @param string $condition
  880. * @param string $fields
  881. * @param string $funcName
  882. * @access public
  883. * @return object the dao object self.
  884. */
  885. public function batchCheckIF($condition, $fields, $funcName) {
  886. if (!$condition) {
  887. return $this;
  888. }
  889. $fields = explode(',', str_replace(' ', '', $fields));
  890. $funcArgs = func_get_args();
  891. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  892. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  893. }
  894. foreach ($fields as $fieldName) {
  895. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  896. }
  897. return $this;
  898. }
  899. /**
  900. * Check the fields according the the database schema.
  901. *
  902. * @param string $skipFields fields to skip checking
  903. * @access public
  904. * @return object the dao object self.
  905. */
  906. public function autoCheck($skipFields = '') {
  907. $fields = $this->getFieldsType();
  908. $skipFields = ",$skipFields,";
  909. foreach ($fields as $fieldName => $validater) {
  910. if (strpos($skipFields, $fieldName) !== false) {
  911. continue; // skip it.
  912. }
  913. if (!isset($this->sqlobj->data->$fieldName)) {
  914. continue;
  915. }
  916. if ($validater['rule'] == 'skip') {
  917. continue;
  918. }
  919. $options = array();
  920. if (isset($validater['options'])) {
  921. $options = array_values($validater['options']);
  922. }
  923. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  924. ${"arg$i"} = isset($options[$i]) ? $options[$i] : null;
  925. }
  926. $this->check($fieldName, $validater['rule'], $arg0, $arg1, $arg2);
  927. }
  928. return $this;
  929. }
  930. /**
  931. * 检查表是否存在
  932. * @param type $tableName
  933. * @return type
  934. */
  935. public function tableExist($tableName) {
  936. $this->reset();
  937. $this->setMethod('select');
  938. $sql = "SELECT 1 FROM `$tableName` LIMIT 1";
  939. $ret = false;
  940. try {
  941. if ($this->slaveDBH and $this->method == 'select') {
  942. $ret = $this->slaveDBH->query($sql)->fetchAll();
  943. } else {
  944. $ret = $this->dbh->query($sql)->fetchAll();
  945. }
  946. } catch (\Exception $exc) { # 表不存在的时候直接进异常处理逻辑.
  947. CLog::err($exc->getMessage());
  948. return false;
  949. }
  950. // Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
  951. return $ret !== FALSE; # false代表表不存在
  952. }
  953. public function Ping() {
  954. try {
  955. $this->dbh->getAttribute(PDO::ATTR_SERVER_INFO);
  956. } catch (\PDOException $e) {
  957. if (strpos($e->getMessage(), 'MySQL server has gone away') !== false) {
  958. return false;
  959. }
  960. }
  961. return true;
  962. }
  963. /**
  964. * Log the error.
  965. *
  966. * For the error notice, see module/common/lang.
  967. *
  968. * @param string $checkType the check rule
  969. * @param string $fieldName the field name
  970. * @param string $fieldLabel the field label
  971. * @param array $funcArgs the args
  972. * @access public
  973. * @return void
  974. */
  975. public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array()) {
  976. global $lang;
  977. $error = $lang->error->$checkType;
  978. $replaces = array_merge(array($fieldLabel), $funcArgs); // the replace values.
  979. /* Just a string, cycle the $replaces. */
  980. if (!is_array($error)) {
  981. foreach ($replaces as $replace) {
  982. $pos = strpos($error, '%s');
  983. if ($pos === false) {
  984. break;
  985. }
  986. $error = substr($error, 0, $pos) . $replace . substr($error, $pos + 2);
  987. }
  988. } else {/* If the error define is an array, select the one which %s counts match the $replaces. */
  989. /* Remove the empty items. */
  990. foreach ($replaces as $key => $value) {
  991. if (is_null($value)) {
  992. unset($replaces[$key]);
  993. }
  994. }
  995. $replacesCount = count($replaces);
  996. foreach ($error as $errorString) {
  997. if (substr_count($errorString, '%s') == $replacesCount) {
  998. $error = vsprintf($errorString, $replaces);
  999. }
  1000. }
  1001. }
  1002. dao::$errors[$fieldName][] = $error;
  1003. }
  1004. /**
  1005. * Judge any error or not.
  1006. *
  1007. * @access public
  1008. * @return bool
  1009. */
  1010. public static function isError() {
  1011. return !empty(dao::$errors);
  1012. }
  1013. /**
  1014. * Get the errors.
  1015. *
  1016. * @param boolean $join
  1017. * @access public
  1018. * @return array
  1019. */
  1020. public static function getError($join = false) {
  1021. $errors = dao::$errors;
  1022. dao::$errors = array(); # Must clear it.
  1023. if (!$join) {
  1024. return $errors;
  1025. }
  1026. if (is_array($errors)) {
  1027. $message = '';
  1028. foreach ($errors as $item) {
  1029. is_array($item) ? $message .= join('\n', $item) . '\n' : $message .= $item . '\n';
  1030. }
  1031. return $message;
  1032. }
  1033. }
  1034. /**
  1035. * Get the defination of fields of the table.
  1036. *
  1037. * @access private
  1038. * @return array
  1039. */
  1040. private function getFieldsType() {
  1041. try {
  1042. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  1043. $sql = "DESC $this->table";
  1044. $rawFields = $this->dbh->query($sql)->fetchAll();
  1045. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  1046. } catch (\PDOException $e) {
  1047. $this->sqlError($e);
  1048. }
  1049. foreach ($rawFields as $rawField) {
  1050. $firstPOS = strpos($rawField->type, '(');
  1051. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  1052. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  1053. $field = array();
  1054. if ($type == 'enum' or $type == 'set') {
  1055. $rangeBegin = $firstPOS + 2; // Remove the first quote.
  1056. $rangeEnd = strrpos($rawField->type, ')') - 1; // Remove the last quote.
  1057. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  1058. $field['rule'] = 'reg';
  1059. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  1060. } elseif ($type == 'char') {
  1061. $begin = $firstPOS + 1;
  1062. $end = strpos($rawField->type, ')', $begin);
  1063. $length = substr($rawField->type, $begin, $end - $begin);
  1064. $field['rule'] = 'length';
  1065. $field['options']['max'] = $length;
  1066. $field['options']['min'] = 0;
  1067. } elseif ($type == 'int') {
  1068. $field['rule'] = 'int';
  1069. } elseif ($type == 'float' or $type == 'double') {
  1070. $field['rule'] = 'float';
  1071. } elseif ($type == 'date') {
  1072. $field['rule'] = 'date';
  1073. } else {
  1074. $field['rule'] = 'skip';
  1075. }
  1076. $fields[$rawField->field] = $field;
  1077. }
  1078. return $fields;
  1079. }
  1080. /**
  1081. * Process SQL error by code.
  1082. *
  1083. * @param object $exception
  1084. * @access public
  1085. * @return void
  1086. */
  1087. public function sqlError($exception) {
  1088. $errorInfo = $exception->errorInfo;
  1089. $errorCode = $errorInfo[1];
  1090. $errorMsg = $errorInfo[2];
  1091. $message = $exception->getMessage();
  1092. if (strpos($this->repairCode, "|$errorCode|") !== false #
  1093. or ( $errorCode == '1016' and strpos($errorMsg, 'errno: 145') !== false)) {
  1094. $message .= ' repairTable';
  1095. }
  1096. $sql = $this->sqlobj->get();
  1097. $this->triggerError($message . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
  1098. }
  1099. }
  1100. /**
  1101. * The SQL class.
  1102. *
  1103. * @package framework
  1104. */
  1105. class sql {
  1106. /**
  1107. * The max count of params of all methods.
  1108. *
  1109. */
  1110. const MAX_ARGS = 3;
  1111. /**
  1112. * The sql string.
  1113. *
  1114. * @var string
  1115. * @access public
  1116. */
  1117. public $sql = '';
  1118. /**
  1119. * The global $dbh.
  1120. *
  1121. *
  1122. * @access protected
  1123. */
  1124. protected $dbh;
  1125. /**
  1126. * The data to update or insert.
  1127. *
  1128. * @var mix
  1129. * @access protected
  1130. */
  1131. public $data;
  1132. /**
  1133. * Is the first time to call set.
  1134. *
  1135. * @var bool
  1136. * @access private;
  1137. */
  1138. private $isFirstSet = true;
  1139. /**
  1140. * If in the logic of judge condition or not.
  1141. *
  1142. * @var bool
  1143. * @access private;
  1144. */
  1145. private $inCondition = false;
  1146. /**
  1147. * The condition is true or not.
  1148. *
  1149. * @var bool
  1150. * @access private;
  1151. */
  1152. private $conditionIsTrue = false;
  1153. /**
  1154. * Magic quote or not.
  1155. *
  1156. * @var bool
  1157. * @access public
  1158. */
  1159. public $magicQuote;
  1160. /**
  1161. * The construct function. user factory() to instance it.
  1162. *
  1163. * @param string $table
  1164. * @access private
  1165. * @return void
  1166. */
  1167. private function __construct($table = '') {
  1168. global $dbh;
  1169. $this->dbh = $dbh;
  1170. $this->magicQuote = false; // get_magic_quotes_gpc();
  1171. }
  1172. /**
  1173. * The factory method.
  1174. *
  1175. * @param string $table
  1176. * @access public
  1177. * @return object the sql object.
  1178. */
  1179. public static function factory($table = '') {
  1180. return new sql($table);
  1181. }
  1182. /**
  1183. * The sql is select.
  1184. *
  1185. * @param string $field
  1186. * @access public
  1187. * @return object the sql object.
  1188. */
  1189. public static function select($field = '*') {
  1190. $sqlobj = self::factory();
  1191. $sqlobj->sql = "SELECT $field ";
  1192. return $sqlobj;
  1193. }
  1194. /**
  1195. * The sql is update.
  1196. *
  1197. * @param string $table
  1198. * @access public
  1199. * @return object the sql object.
  1200. */
  1201. public static function update($table) {
  1202. $sqlobj = self::factory();
  1203. $sqlobj->sql = "UPDATE $table SET ";
  1204. return $sqlobj;
  1205. }
  1206. /**
  1207. * The sql is insert.
  1208. *
  1209. * @param string $table
  1210. * @access public
  1211. * @return object the sql object.
  1212. */
  1213. public static function insert($table) {
  1214. $sqlobj = self::factory();
  1215. $sqlobj->sql = "INSERT INTO $table SET ";
  1216. return $sqlobj;
  1217. }
  1218. /**
  1219. * The sql is insert.
  1220. *
  1221. * @param string $table
  1222. * @access public
  1223. * @return object the sql object.
  1224. */
  1225. public static function del($table) {
  1226. $sqlobj = self::factory();
  1227. $sqlobj->sql = "DELETE FROM $table WHERE ";
  1228. return $sqlobj;
  1229. }
  1230. /**
  1231. * The sql is replace.
  1232. *
  1233. * @param string $table
  1234. * @access public
  1235. * @return object the sql object.
  1236. */
  1237. public static function replace($table) {
  1238. $sqlobj = self::factory();
  1239. $sqlobj->sql = "REPLACE $table SET ";
  1240. return $sqlobj;
  1241. }
  1242. /**
  1243. * The sql is delete.
  1244. *
  1245. * @access public
  1246. * @return object the sql object.
  1247. */
  1248. public static function delete() {
  1249. $sqlobj = self::factory();
  1250. $sqlobj->sql = "DELETE ";
  1251. return $sqlobj;
  1252. }
  1253. /**
  1254. * Join the data items by key = value.
  1255. *
  1256. * @param object $data
  1257. * @access public
  1258. * @return object the sql object.
  1259. */
  1260. public function data($data) {
  1261. $data = (object) $data;
  1262. foreach ($data as $field => $value) {
  1263. if (!preg_match('|^\w+$|', $field)) {
  1264. unset($data->$field);
  1265. continue;
  1266. }
  1267. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  1268. }
  1269. $this->data = $data;
  1270. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  1271. return $this;
  1272. }
  1273. /**
  1274. * Aadd an '(' at left.
  1275. *
  1276. * @param int $count
  1277. * @access public
  1278. * @return ojbect the sql object.
  1279. */
  1280. public function markLeft($count = 1) {
  1281. $this->sql .= str_repeat('(', $count);
  1282. return $this;
  1283. }
  1284. /**
  1285. * Add an ')' ad right.
  1286. *
  1287. * @param int $count
  1288. * @access public
  1289. * @return object the sql object.
  1290. */
  1291. public function markRight($count = 1) {
  1292. $this->sql .= str_repeat(')', $count);
  1293. return $this;
  1294. }
  1295. /**
  1296. * The set part.
  1297. *
  1298. * @param string $set
  1299. * @access public
  1300. * @return object the sql object.
  1301. */
  1302. public function set($set) {
  1303. if ($this->isFirstSet) {
  1304. $this->sql .= " $set ";
  1305. $this->isFirstSet = false;
  1306. } else {
  1307. $this->sql .= ", $set";
  1308. }
  1309. return $this;
  1310. }
  1311. /**
  1312. * Create the from part.
  1313. *
  1314. * @param string $table
  1315. * @access public
  1316. * @return object the sql object.
  1317. */
  1318. public function from($table) {
  1319. $this->sql .= "FROM $table";
  1320. return $this;
  1321. }
  1322. /**
  1323. * Create the Alias part.
  1324. *
  1325. * @param string $alias
  1326. * @access public
  1327. * @return object the sql object.
  1328. */
  1329. public function alias($alias) {
  1330. $this->sql .= " AS $alias ";
  1331. return $this;
  1332. }
  1333. /**
  1334. * Create the left join part.
  1335. *
  1336. * @param string $table
  1337. * @access public
  1338. * @return object the sql object.
  1339. */
  1340. public function leftJoin($table) {
  1341. $this->sql .= " LEFT JOIN $table";
  1342. return $this;
  1343. }
  1344. /**
  1345. * Create the on part.
  1346. *
  1347. * @param string $condition
  1348. * @access public
  1349. * @return object the sql object.
  1350. */
  1351. public function on($condition) {
  1352. $this->sql .= " ON $condition ";
  1353. return $this;
  1354. }
  1355. /**
  1356. * Begin condition judge.
  1357. *
  1358. * @param bool $condition
  1359. * @access public
  1360. * @return object the sql object.
  1361. */
  1362. public function beginIF($condition) {
  1363. $this->inCondition = true;
  1364. $this->conditionIsTrue = $condition;
  1365. return $this;
  1366. }
  1367. /**
  1368. * End the condition judge.
  1369. *
  1370. * @access public
  1371. * @return object the sql object.
  1372. */
  1373. public function fi() {
  1374. $this->inCondition = false;
  1375. $this->conditionIsTrue = false;
  1376. return $this;
  1377. }
  1378. /**
  1379. * Create the where part.
  1380. *
  1381. * @param string $arg1 the field name
  1382. * @param string $arg2 the operator
  1383. * @param string $arg3 the value
  1384. * @access public
  1385. * @return object the sql object.
  1386. */
  1387. public function where($arg1, $arg2 = null, $arg3 = null) {
  1388. if ($this->inCondition and !$this->conditionIsTrue) {
  1389. return $this;
  1390. }
  1391. if ($arg3 !== null) {
  1392. $value = $this->quote($arg3);
  1393. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  1394. } else {
  1395. $condition = $arg1;
  1396. }
  1397. $this->sql .= ' ' . DAO::WHERE . " $condition ";
  1398. return $this;
  1399. }
  1400. /**
  1401. * Create the AND part.
  1402. *
  1403. * @param string $condition
  1404. * @access public
  1405. * @return object the sql object.
  1406. */
  1407. public function andWhere($condition) {
  1408. if ($this->inCondition and !$this->conditionIsTrue) {
  1409. return $this;
  1410. }
  1411. $this->sql .= " AND $condition ";
  1412. return $this;
  1413. }
  1414. /**
  1415. * Create the OR part.
  1416. *
  1417. * @param bool $condition
  1418. * @access public
  1419. * @return object the sql object.
  1420. */
  1421. public function orWhere($condition) {
  1422. if ($this->inCondition and !$this->conditionIsTrue) {
  1423. return $this;
  1424. }
  1425. $this->sql .= " OR $condition ";
  1426. return $this;
  1427. }
  1428. /**
  1429. * Create the '='.
  1430. *
  1431. * @param string $value
  1432. * @access public
  1433. * @return object the sql object.
  1434. */
  1435. public function eq($value) {
  1436. if ($this->inCondition and !$this->conditionIsTrue) {
  1437. return $this;
  1438. }
  1439. $this->sql .= " = " . $this->quote($value);
  1440. return $this;
  1441. }
  1442. /**
  1443. * Create '!='.
  1444. *
  1445. * @param string $value
  1446. * @access public
  1447. * @return void the sql object.
  1448. */
  1449. public function ne($value) {
  1450. if ($this->inCondition and !$this->conditionIsTrue) {
  1451. return $this;
  1452. }
  1453. $this->sql .= " != " . $this->quote($value);
  1454. return $this;
  1455. }
  1456. /**
  1457. * Create '>'.
  1458. *
  1459. * @param string $value
  1460. * @access public
  1461. * @return object the sql object.
  1462. */
  1463. public function gt($value) {
  1464. if ($this->inCondition and !$this->conditionIsTrue) {
  1465. return $this;
  1466. }
  1467. $this->sql .= " > " . $this->quote($value);
  1468. return $this;
  1469. }
  1470. /**
  1471. * Create '>='.
  1472. *
  1473. * @param string $value
  1474. * @access public
  1475. * @return object the sql object.
  1476. */
  1477. public function ge($value) {
  1478. if ($this->inCondition and !$this->conditionIsTrue) {
  1479. return $this;
  1480. }
  1481. $this->sql .= " >= " . $this->quote($value);
  1482. return $this;
  1483. }
  1484. /**
  1485. * Create '<'.
  1486. *
  1487. * @param mixed $value
  1488. * @access public
  1489. * @return object the sql object.
  1490. */
  1491. public function lt($value) {
  1492. if ($this->inCondition and !$this->conditionIsTrue) {
  1493. return $this;
  1494. }
  1495. $this->sql .= " < " . $this->quote($value);
  1496. return $this;
  1497. }
  1498. /**
  1499. * Create '<='.
  1500. *
  1501. * @param mixed $value
  1502. * @access public
  1503. * @return object the sql object.
  1504. */
  1505. public function le($value) {
  1506. if ($this->inCondition && !$this->conditionIsTrue) {
  1507. return $this;
  1508. }
  1509. $this->sql .= " <= " . $this->quote($value);
  1510. return $this;
  1511. }
  1512. /**
  1513. * Create "between and"
  1514. *
  1515. * @param string $min
  1516. * @param string $max
  1517. * @access public
  1518. * @return object the sql object.
  1519. */
  1520. public function between($min, $max) {
  1521. if ($this->inCondition and !$this->conditionIsTrue) {
  1522. return $this;
  1523. }
  1524. $min = $this->quote($min);
  1525. $max = $this->quote($max);
  1526. $this->sql .= " BETWEEN $min AND $max ";
  1527. return $this;
  1528. }
  1529. /**
  1530. * Create in part.
  1531. *
  1532. * @param string|array $ids list string by ',' or an array
  1533. * @access public
  1534. * @return object the sql object.
  1535. */
  1536. public function in($ids) {
  1537. // var_dump($ids);
  1538. if ($this->inCondition and !$this->conditionIsTrue) {
  1539. return $this;
  1540. }
  1541. $this->sql .= self::dbIN($ids);
  1542. return $this;
  1543. }
  1544. /**
  1545. * Create the in('a', 'b') string.
  1546. *
  1547. * @param string|array $ids the id lists, can be a array or a string with ids joined with comma.
  1548. * @static
  1549. * @access public
  1550. * @return string the string like IN('a', 'b').
  1551. */
  1552. private static function dbIN($ids) {
  1553. if (is_array($ids)) {
  1554. return "IN ('" . join("','", $ids) . "')";
  1555. }
  1556. return "IN ('" . str_replace(',', "','", str_replace(' ', '', $ids)) . "')";
  1557. }
  1558. /**
  1559. * Create not in part.
  1560. *
  1561. * @param string|array $ids list string by ',' or an array
  1562. * @access public
  1563. * @return object the sql object.
  1564. */
  1565. public function notin($ids) {
  1566. if ($this->inCondition and !$this->conditionIsTrue) {
  1567. return $this;
  1568. }
  1569. $this->sql .= ' NOT ' . self::dbIN($ids);
  1570. return $this;
  1571. }
  1572. /**
  1573. * Create the like by part.
  1574. *
  1575. * @param string $string
  1576. * @access public
  1577. * @return object the sql object.
  1578. */
  1579. public function like($string) {
  1580. if ($this->inCondition and !$this->conditionIsTrue) {
  1581. return $this;
  1582. }
  1583. $this->sql .= " LIKE " . $this->quote($string);
  1584. return $this;
  1585. }
  1586. /**
  1587. * Create the not like by part.
  1588. *
  1589. * @param string $string
  1590. * @access public
  1591. * @return object the sql object.
  1592. */
  1593. public function notLike($string) {
  1594. if ($this->inCondition and !$this->conditionIsTrue) {
  1595. return $this;
  1596. }
  1597. $this->sql .= "NOT LIKE " . $this->quote($string);
  1598. return $this;
  1599. }
  1600. /**
  1601. * Create the find_in_set by part.
  1602. *
  1603. * @param int $str
  1604. * @param int $strList
  1605. * @access public
  1606. * @return object the sql object.
  1607. */
  1608. public function findInSet($str, $strList) {
  1609. if ($this->inCondition and !$this->conditionIsTrue) {
  1610. return $this;
  1611. }
  1612. $this->sql .= "FIND_IN_SET(" . $str . "," . $strList . ")";
  1613. }
  1614. /**
  1615. * Create the order by part.
  1616. *
  1617. * @param string $order
  1618. * @access public
  1619. * @return object the sql object.
  1620. */
  1621. public function orderBy($order) {
  1622. if ($this->inCondition and !$this->conditionIsTrue) {
  1623. return $this;
  1624. }
  1625. $order = str_replace(array('|', '', '_'), ' ', $order);
  1626. /* Add "`" in order string. */
  1627. /* When order has limit string. */
  1628. $pos = stripos($order, 'limit');
  1629. $orders = $pos ? substr($order, 0, $pos) : $order;
  1630. $limit = $pos ? substr($order, $pos) : '';
  1631. $orders = explode(',', $orders);
  1632. foreach ($orders as $i => $order) {
  1633. $orderParse = explode(' ', trim($order));
  1634. foreach ($orderParse as $key => $value) {
  1635. $value = trim($value);
  1636. if (empty($value) #
  1637. or strtolower($value) == 'desc' #
  1638. or strtolower($value) == 'asc') {
  1639. continue;
  1640. }
  1641. $field = trim($value, '`');
  1642. /* such as t1.id field. */
  1643. if (strpos($value, '.') !== false) {
  1644. list($table, $field) = explode('.', $field);
  1645. }
  1646. $field = "`$field`";
  1647. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  1648. unset($table);
  1649. }
  1650. $orders[$i] = join(' ', $orderParse);
  1651. }
  1652. $order = join(',', $orders) . ' ' . $limit;
  1653. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  1654. return $this;
  1655. }
  1656. /**
  1657. * Create the limit part.
  1658. *
  1659. * @param string $limit
  1660. * @access public
  1661. * @return object the sql object.
  1662. */
  1663. public function limit($limit) {
  1664. if (empty($limit)) {
  1665. return $this;
  1666. }
  1667. stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  1668. return $this;
  1669. }
  1670. /**
  1671. * Create the groupby part.
  1672. *
  1673. * @param string $groupBy
  1674. * @access public
  1675. * @return object the sql object.
  1676. */
  1677. public function groupBy($groupBy) {
  1678. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  1679. return $this;
  1680. }
  1681. /**
  1682. * Create the having part.
  1683. *
  1684. * @param string $having
  1685. * @access public
  1686. * @return object the sql object.
  1687. */
  1688. public function having($having) {
  1689. $this->sql .= ' ' . DAO::HAVING . " $having";
  1690. return $this;
  1691. }
  1692. /**
  1693. * Get the sql string.
  1694. *
  1695. * @access public
  1696. * @return string
  1697. */
  1698. public function get() {
  1699. return $this->sql;
  1700. }
  1701. /**
  1702. * Uuote a var.
  1703. *
  1704. * @param mixed $value
  1705. * @access public
  1706. * @return mixed
  1707. */
  1708. public function quote($value) {
  1709. if ($this->magicQuote) {
  1710. $value = stripslashes($value);
  1711. }
  1712. if (!is_string($value)) {
  1713. $value = "$value";
  1714. }
  1715. return $this->dbh->quote($value);
  1716. }
  1717. }