DbConnection.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  1. <?php
  2. namespace GatewayWorker\Lib;
  3. /**
  4. * 数据库连接类,依赖mysql_pdo扩展
  5. * 在https://github.com/auraphp/Aura.SqlQuery的基础上修改而成
  6. */
  7. class DbConnection
  8. {
  9. /**
  10. * SELECT
  11. * @var array
  12. */
  13. protected $union = array();
  14. /**
  15. * 是否是更新
  16. * @var bool
  17. */
  18. protected $for_update = false;
  19. /**
  20. * 选择的列
  21. * @var array
  22. */
  23. protected $cols = array();
  24. /**
  25. * 从哪些表里面SELECT
  26. * @var array
  27. */
  28. protected $from = array();
  29. /**
  30. * $from 当前的 key
  31. * @var int
  32. */
  33. protected $from_key = -1;
  34. /**
  35. * GROUP BY 的列
  36. * @var array
  37. */
  38. protected $group_by = array();
  39. /**
  40. * HAVING 条件数组.
  41. * @var array
  42. */
  43. protected $having = array();
  44. /**
  45. * HAVING 语句中绑定的值.
  46. * @var array
  47. */
  48. protected $bind_having = array();
  49. /**
  50. * 每页多少条记录
  51. * @var int
  52. */
  53. protected $paging = 10;
  54. /**
  55. * sql中绑定的值
  56. * @var array
  57. */
  58. protected $bind_values = array();
  59. /**
  60. * WHERE 条件.
  61. * @var array
  62. */
  63. protected $where = array();
  64. /**
  65. * WHERE语句绑定的值
  66. * @var array
  67. */
  68. protected $bind_where = array();
  69. /**
  70. * ORDER BY 的列
  71. * @var array
  72. */
  73. protected $order_by = array();
  74. /**
  75. * ORDER BY 的排序方式,默认为升序
  76. * @var bool
  77. */
  78. protected $order_asc = true;
  79. /**
  80. * SELECT多少记录
  81. * @var int
  82. */
  83. protected $limit = 0;
  84. /**
  85. * 返回记录的游标
  86. * @var int
  87. */
  88. protected $offset = 0;
  89. /**
  90. * flags 列表
  91. * @var array
  92. */
  93. protected $flags = array();
  94. /**
  95. * 操作哪个表
  96. * @var string
  97. */
  98. protected $table;
  99. /**
  100. * 表.列 和 last-insert-id 映射
  101. * @var array
  102. */
  103. protected $last_insert_id_names = array();
  104. /**
  105. * INSERT 或者 UPDATE 的列
  106. * @param array
  107. */
  108. protected $col_values;
  109. /**
  110. * 返回的列
  111. * @var array
  112. */
  113. protected $returning = array();
  114. /**
  115. * sql的类型 SELECT INSERT DELETE UPDATE
  116. * @var string
  117. */
  118. protected $type = '';
  119. /**
  120. * pdo 实例
  121. * @var pdo
  122. */
  123. protected $pdo;
  124. /**
  125. * PDO statement 实例
  126. * @var PDO statement
  127. */
  128. protected $sQuery;
  129. /**
  130. * 数据库用户名密码等配置
  131. * @var array
  132. */
  133. protected $settings = array();
  134. /**
  135. * sql的参数
  136. * @var array
  137. */
  138. protected $parameters = array();
  139. /**
  140. * 最后一条直行的sql
  141. * @var string
  142. */
  143. protected $lastSql = '';
  144. /**
  145. * 选择哪些列
  146. * @param string/array $cols
  147. */
  148. public function select($cols = '*')
  149. {
  150. $this->type = 'SELECT';
  151. if(!is_array($cols))
  152. {
  153. $cols = array($cols);
  154. }
  155. $this->cols($cols);
  156. return $this;
  157. }
  158. /**
  159. * 从哪个表删除
  160. * @param string $table
  161. * @return self
  162. */
  163. public function delete($table)
  164. {
  165. $this->type = 'DELETE';
  166. $this->table = $this->quoteName($table);
  167. $this->fromRaw($this->quoteName($table));
  168. return $this;
  169. }
  170. /**
  171. * 更新哪个表
  172. * @param string $table
  173. */
  174. public function update($table)
  175. {
  176. $this->type = 'UPDATE';
  177. $this->table = $this->quoteName($table);
  178. return $this;
  179. }
  180. /**
  181. * 向哪个表插入
  182. * @param string $table
  183. */
  184. public function insert($table)
  185. {
  186. $this->type = 'INSERT';
  187. $this->table = $this->quoteName($table);
  188. return $this;
  189. }
  190. /**
  191. *
  192. * 设置 SQL_CALC_FOUND_ROWS 标记.
  193. * @param bool
  194. * @return self
  195. */
  196. public function calcFoundRows($enable = true)
  197. {
  198. $this->setFlag('SQL_CALC_FOUND_ROWS', $enable);
  199. return $this;
  200. }
  201. /**
  202. * 设置 SQL_CACHE 标记
  203. * @param bool
  204. * @return self
  205. */
  206. public function cache($enable = true)
  207. {
  208. $this->setFlag('SQL_CACHE', $enable);
  209. return $this;
  210. }
  211. /**
  212. * 设置 SQL_NO_CACHE 标记
  213. * @param bool
  214. * @return self
  215. */
  216. public function noCache($enable = true)
  217. {
  218. $this->setFlag('SQL_NO_CACHE', $enable);
  219. return $this;
  220. }
  221. /**
  222. * 设置 STRAIGHT_JOIN 标记.
  223. * @param bool
  224. * @return self
  225. */
  226. public function straightJoin($enable = true)
  227. {
  228. $this->setFlag('STRAIGHT_JOIN', $enable);
  229. return $this;
  230. }
  231. /**
  232. * 设置 HIGH_PRIORITY 标记
  233. * @param bool
  234. * @return self
  235. */
  236. public function highPriority($enable = true)
  237. {
  238. $this->setFlag('HIGH_PRIORITY', $enable);
  239. return $this;
  240. }
  241. /**
  242. * 设置 SQL_SMALL_RESULT 标记
  243. * @param bool
  244. * @return self
  245. */
  246. public function smallResult($enable = true)
  247. {
  248. $this->setFlag('SQL_SMALL_RESULT', $enable);
  249. return $this;
  250. }
  251. /**
  252. * 设置 SQL_BIG_RESULT 标记
  253. * @param bool
  254. * @return self
  255. */
  256. public function bigResult($enable = true)
  257. {
  258. $this->setFlag('SQL_BIG_RESULT', $enable);
  259. return $this;
  260. }
  261. /**
  262. * 设置 SQL_BUFFER_RESULT 标记
  263. * @param bool
  264. * @return self
  265. */
  266. public function bufferResult($enable = true)
  267. {
  268. $this->setFlag('SQL_BUFFER_RESULT', $enable);
  269. return $this;
  270. }
  271. /**
  272. * 设置 FOR UPDATE 标记
  273. * @param bool
  274. * @return self
  275. */
  276. public function forUpdate($enable = true)
  277. {
  278. $this->for_update = (bool) $enable;
  279. return $this;
  280. }
  281. /**
  282. * 设置 DISTINCT 标记
  283. * @param bool
  284. * @return self
  285. */
  286. public function distinct($enable = true)
  287. {
  288. $this->setFlag('DISTINCT', $enable);
  289. return $this;
  290. }
  291. /**
  292. * 设置 LOW_PRIORITY 标记
  293. * @param bool $enable
  294. * @return self
  295. */
  296. public function lowPriority($enable = true)
  297. {
  298. $this->setFlag('LOW_PRIORITY', $enable);
  299. return $this;
  300. }
  301. /**
  302. * 设置 IGNORE 标记
  303. * @param bool $enable
  304. * @return self
  305. */
  306. public function ignore($enable = true)
  307. {
  308. $this->setFlag('IGNORE', $enable);
  309. return $this;
  310. }
  311. /**
  312. * 设置 QUICK 标记
  313. * @param bool $enable
  314. * @return self
  315. */
  316. public function quick($enable = true)
  317. {
  318. $this->setFlag('QUICK', $enable);
  319. return $this;
  320. }
  321. /**
  322. * 设置 DELAYED 标记
  323. * @param bool $enable
  324. * @return self
  325. */
  326. public function delayed($enable = true)
  327. {
  328. $this->setFlag('DELAYED', $enable);
  329. return $this;
  330. }
  331. /**
  332. * 序列化
  333. * @return string
  334. */
  335. public function __toString()
  336. {
  337. $union = '';
  338. if ($this->union) {
  339. $union = implode(' ', $this->union) . ' ';
  340. }
  341. return $union . $this->build();
  342. }
  343. /**
  344. * 设置每页多少条记录
  345. * @param int
  346. * @return self
  347. */
  348. public function setPaging($paging)
  349. {
  350. $this->paging = (int) $paging;
  351. return $this;
  352. }
  353. /**
  354. * 获取每页多少条记录
  355. * @return int
  356. */
  357. public function getPaging()
  358. {
  359. return $this->paging;
  360. }
  361. /**
  362. * 获取绑定在占位符上的值
  363. */
  364. public function getBindValues()
  365. {
  366. switch($this->type)
  367. {
  368. case 'SELECT':
  369. return $this->getBindValuesSELECT();
  370. case 'DELETE':
  371. case 'UPDATE':
  372. case 'INSERT':
  373. return $this->getBindValuesCOMMON();
  374. default :
  375. throw new \Exception("type err");
  376. }
  377. }
  378. /**
  379. * 获取绑定在占位符上的值
  380. * @return array
  381. */
  382. public function getBindValuesSELECT()
  383. {
  384. $bind_values = $this->bind_values;
  385. $i = 1;
  386. foreach ($this->bind_where as $val) {
  387. $bind_values[$i] = $val;
  388. $i ++;
  389. }
  390. foreach ($this->bind_having as $val) {
  391. $bind_values[$i] = $val;
  392. $i ++;
  393. }
  394. return $bind_values;
  395. }
  396. /**
  397. *
  398. * SELECT选择哪些列
  399. * @param mixed
  400. * @return null
  401. */
  402. protected function addColSELECT($key, $val)
  403. {
  404. if (is_string($key)) {
  405. $this->cols[$val] = $key;
  406. } else {
  407. $this->addColWithAlias($val);
  408. }
  409. }
  410. /**
  411. * SELECT增加选择的列
  412. * @param string
  413. * @return null
  414. */
  415. protected function addColWithAlias($spec)
  416. {
  417. $parts = explode(' ', $spec);
  418. $count = count($parts);
  419. if ($count == 2) {
  420. $this->cols[$parts[1]] = $parts[0];
  421. } elseif ($count == 3 && strtoupper($parts[1]) == 'AS') {
  422. $this->cols[$parts[2]] = $parts[0];
  423. } else {
  424. $this->cols[] = $spec;
  425. }
  426. }
  427. /**
  428. * from 哪个表
  429. * @param string $table
  430. * @return self
  431. */
  432. public function from($table)
  433. {
  434. return $this->fromRaw($this->quoteName($table));
  435. }
  436. /**
  437. * from的表
  438. * @param string $table
  439. * @return self
  440. */
  441. public function fromRaw($table)
  442. {
  443. $this->from[] = array($table);
  444. $this->from_key ++;
  445. return $this;
  446. }
  447. /**
  448. *
  449. * 子查询
  450. * @param string $table
  451. * @param string $name The alias name for the sub-select.
  452. * @return self
  453. */
  454. public function fromSubSelect($table, $name)
  455. {
  456. $this->from[] = array( "($table) AS " . $this->quoteName($name));
  457. $this->from_key ++;
  458. return $this;
  459. }
  460. /**
  461. * 增加join语句
  462. * @param string $join inner, left, natural
  463. * @param string $table
  464. * @param string $cond
  465. * @return self
  466. * @throws Exception
  467. */
  468. public function join($table, $cond = null, $type = '')
  469. {
  470. return $this->joinInternal($type, $table, $cond);
  471. }
  472. /**
  473. * 增加join语句
  474. * @param string $join inner, left, natural
  475. * @param string $table
  476. * @param string $cond
  477. * @return self
  478. * @throws Exception
  479. */
  480. protected function joinInternal($join, $table, $cond = null)
  481. {
  482. if (! $this->from) {
  483. throw new \Exception('Cannot join() without from()');
  484. }
  485. $join = strtoupper(ltrim("$join JOIN"));
  486. $table = $this->quoteName($table);
  487. $cond = $this->fixJoinCondition($cond);
  488. $this->from[$this->from_key][] = rtrim("$join $table $cond");
  489. return $this;
  490. }
  491. /**
  492. * quote
  493. * @param string $cond
  494. * @return string
  495. *
  496. */
  497. protected function fixJoinCondition($cond)
  498. {
  499. if (! $cond) {
  500. return;
  501. }
  502. $cond = $this->quoteNamesIn($cond);
  503. if (strtoupper(substr(ltrim($cond), 0, 3)) == 'ON ') {
  504. return $cond;
  505. }
  506. if (strtoupper(substr(ltrim($cond), 0, 6)) == 'USING ') {
  507. return $cond;
  508. }
  509. return 'ON ' . $cond;
  510. }
  511. /**
  512. * inner join
  513. * @param string $spec
  514. * @param string $cond
  515. * @return self
  516. * @throws Exception
  517. */
  518. public function innerJoin($table, $cond = null)
  519. {
  520. return $this->joinInternal('INNER', $table, $cond);
  521. }
  522. /**
  523. * left join
  524. * @param string $table
  525. * @param string $cond
  526. * @return self
  527. * @throws Exception
  528. */
  529. public function leftJoin($table, $cond = null)
  530. {
  531. return $this->joinInternal('LEFT', $table, $cond);
  532. }
  533. /**
  534. * right join
  535. * @param string $table
  536. * @param string $cond
  537. * @return self
  538. * @throws Exception
  539. */
  540. public function rightJoin($table, $cond = null)
  541. {
  542. return $this->joinInternal('RIGHT', $table, $cond);
  543. }
  544. /**
  545. * joinSubSelect
  546. * @param string $join inner, left, natural
  547. * @param string $spec
  548. * @param string $name sub-select 的别名
  549. * @param string $cond
  550. * @return self
  551. * @throws Exception
  552. */
  553. public function joinSubSelect($join, $spec, $name, $cond = null)
  554. {
  555. if (! $this->from) {
  556. throw new \Exception('Cannot join() without from() first.');
  557. }
  558. $join = strtoupper(ltrim("$join JOIN"));
  559. $name = $this->quoteName($name);
  560. $cond = $this->fixJoinCondition($cond);
  561. $this->from[$this->from_key][] = rtrim("$join ($spec) AS $name $cond");
  562. return $this;
  563. }
  564. /**
  565. * group by 语句
  566. * @param array $cols
  567. * @return self
  568. */
  569. public function groupBy(array $cols)
  570. {
  571. foreach ($cols as $col) {
  572. $this->group_by[] = $this->quoteNamesIn($col);
  573. }
  574. return $this;
  575. }
  576. /**
  577. * having 语句
  578. * @param string $cond
  579. * @return self
  580. */
  581. public function having($cond)
  582. {
  583. $this->addClauseCondWithBind('having', 'AND', func_get_args());
  584. return $this;
  585. }
  586. /**
  587. * or having 语句
  588. * @param string $cond The HAVING condition.
  589. * @return self
  590. */
  591. public function orHaving($cond)
  592. {
  593. $this->addClauseCondWithBind('having', 'OR', func_get_args());
  594. return $this;
  595. }
  596. /**
  597. * 设置每页的记录数量
  598. * @param int $page
  599. * @return self
  600. */
  601. public function page($page)
  602. {
  603. $this->limit = 0;
  604. $this->offset = 0;
  605. $page = (int) $page;
  606. if ($page > 0) {
  607. $this->limit = $this->paging;
  608. $this->offset = $this->paging * ($page - 1);
  609. }
  610. return $this;
  611. }
  612. /**
  613. * union
  614. * @return self
  615. */
  616. public function union()
  617. {
  618. $this->union[] = $this->build() . ' UNION';
  619. $this->reset();
  620. return $this;
  621. }
  622. /**
  623. * unionAll
  624. * @return self
  625. */
  626. public function unionAll()
  627. {
  628. $this->union[] = $this->build() . ' UNION ALL';
  629. $this->reset();
  630. return $this;
  631. }
  632. /**
  633. * 重置
  634. * @return null
  635. */
  636. protected function reset()
  637. {
  638. $this->resetFlags();
  639. $this->cols = array();
  640. $this->from = array();
  641. $this->from_key = -1;
  642. $this->where = array();
  643. $this->group_by = array();
  644. $this->having = array();
  645. $this->order_by = array();
  646. $this->limit = 0;
  647. $this->offset = 0;
  648. $this->for_update = false;
  649. }
  650. /**
  651. * 清除所有数据
  652. * @return void
  653. */
  654. protected function resetAll()
  655. {
  656. $this->union = array();
  657. $this->for_update = false;
  658. $this->cols = array();
  659. $this->from = array();
  660. $this->from_key = -1;
  661. $this->group_by = array();
  662. $this->having = array();
  663. $this->bind_having = array();
  664. $this->paging = 10;
  665. $this->bind_values = array();
  666. $this->where = array();
  667. $this->bind_where = array();
  668. $this->order_by = array();
  669. $this->limit = 0;
  670. $this->offset = 0;
  671. $this->flags = array();
  672. $this->table = '';
  673. $this->last_insert_id_names = array();
  674. $this->col_values = array();
  675. $this->returning = array();
  676. $this->parameters = array();
  677. }
  678. /**
  679. * 创建 SELECT SQL
  680. * @return string
  681. */
  682. protected function buildSELECT()
  683. {
  684. return 'SELECT'
  685. . $this->buildFlags()
  686. . $this->buildCols()
  687. . $this->buildFrom()
  688. . $this->buildWhere()
  689. . $this->buildGroupBy()
  690. . $this->buildHaving()
  691. . $this->buildOrderBy()
  692. . $this->buildLimit()
  693. . $this->buildForUpdate();
  694. }
  695. /**
  696. * 创建DELETE SQL
  697. */
  698. protected function buildDELETE()
  699. {
  700. return 'DELETE'
  701. . $this->buildFlags()
  702. . $this->buildFrom()
  703. . $this->buildWhere()
  704. . $this->buildOrderBy()
  705. . $this->buildLimit()
  706. . $this->buildReturning();
  707. }
  708. /**
  709. * 生成SELECT列语句
  710. * @return string
  711. * @throws Exception
  712. */
  713. protected function buildCols()
  714. {
  715. if (! $this->cols) {
  716. throw new \Exception('No columns in the SELECT.');
  717. }
  718. $cols = array();
  719. foreach ($this->cols as $key => $val) {
  720. if (is_int($key)) {
  721. $cols[] = $this->quoteNamesIn($val);
  722. } else {
  723. $cols[] = $this->quoteNamesIn("$val AS $key");
  724. }
  725. }
  726. return $this->indentCsv($cols);
  727. }
  728. /**
  729. * 生成 FROM 语句.
  730. * @return string
  731. */
  732. protected function buildFrom()
  733. {
  734. if (! $this->from) {
  735. return '';
  736. }
  737. $refs = array();
  738. foreach ($this->from as $from) {
  739. $refs[] = implode(' ', $from);
  740. }
  741. return ' FROM' . $this->indentCsv($refs);
  742. }
  743. /**
  744. * 生成 GROUP BY 语句.
  745. * @return string
  746. */
  747. protected function buildGroupBy()
  748. {
  749. if (! $this->group_by) {
  750. return '';
  751. }
  752. return ' GROUP BY' . $this->indentCsv($this->group_by);
  753. }
  754. /**
  755. * 生成 HAVING 语句.
  756. * @return string
  757. */
  758. protected function buildHaving()
  759. {
  760. if (! $this->having) {
  761. return '';
  762. }
  763. return ' HAVING' . $this->indent($this->having);
  764. }
  765. /**
  766. * 生成 FOR UPDATE 语句
  767. * @return string
  768. */
  769. protected function buildForUpdate()
  770. {
  771. if (! $this->for_update) {
  772. return '';
  773. }
  774. return ' FOR UPDATE';
  775. }
  776. /**
  777. * where
  778. * @param string/array $cond
  779. * @param mixed ...$bind
  780. * @return self
  781. */
  782. public function where($cond)
  783. {
  784. if(is_array($cond))
  785. {
  786. foreach($cond as $key=>$val)
  787. {
  788. if(is_string($key))
  789. {
  790. $this->addWhere('AND', array($key, $val));
  791. }
  792. else
  793. {
  794. $this->addWhere('AND', array($val));
  795. }
  796. }
  797. }
  798. else
  799. {
  800. $this->addWhere('AND', func_get_args());
  801. }
  802. return $this;
  803. }
  804. /**
  805. * or where
  806. * @param string/array $cond
  807. * @param mixed ...$bind
  808. * @return self
  809. */
  810. public function orWhere($cond)
  811. {
  812. if(is_array($cond))
  813. {
  814. foreach($cond as $key=>$val)
  815. {
  816. if(is_string($key))
  817. {
  818. $this->addWhere('OR', array($key, $val));
  819. }
  820. else
  821. {
  822. $this->addWhere('OR', array($val));
  823. }
  824. }
  825. }
  826. else
  827. {
  828. $this->addWhere('OR', func_get_args());
  829. }
  830. return $this;
  831. }
  832. /**
  833. * limit
  834. * @param int $limit
  835. * @return self
  836. */
  837. public function limit($limit)
  838. {
  839. $this->limit = (int) $limit;
  840. return $this;
  841. }
  842. /**
  843. * limit offset
  844. * @param int $offset
  845. * @return self
  846. */
  847. public function offset($offset)
  848. {
  849. $this->offset = (int) $offset;
  850. return $this;
  851. }
  852. /**
  853. * orderby.
  854. * @param array $cols
  855. * @return self
  856. */
  857. public function orderBy(array $cols)
  858. {
  859. return $this->addOrderBy($cols);
  860. }
  861. /**
  862. * order by ASC OR DESC
  863. * @param array $cols
  864. * @param bool $order_asc
  865. * @return self
  866. */
  867. public function orderByASC(array $cols, $order_asc = true)
  868. {
  869. $this->order_asc = $order_asc;
  870. return $this->addOrderBy($cols);
  871. }
  872. // -------------abstractquery----------
  873. /**
  874. * 返回逗号分隔的字符串
  875. * @param array $list
  876. * @return string
  877. */
  878. protected function indentCsv(array $list)
  879. {
  880. return ' ' . implode(',', $list);
  881. }
  882. /**
  883. * 返回空格分隔的字符串
  884. * @param array $list
  885. * @return string
  886. */
  887. protected function indent(array $list)
  888. {
  889. return ' ' . implode(' ', $list);
  890. }
  891. /**
  892. * 批量为占位符绑定值
  893. * @param array $bind_values
  894. * @return self
  895. *
  896. */
  897. public function bindValues(array $bind_values)
  898. {
  899. foreach ($bind_values as $key => $val) {
  900. $this->bindValue($key, $val);
  901. }
  902. return $this;
  903. }
  904. /**
  905. * 单个为占位符绑定值
  906. * @param string $name
  907. * @param mixed $value
  908. * @return self
  909. */
  910. public function bindValue($name, $value)
  911. {
  912. $this->bind_values[$name] = $value;
  913. return $this;
  914. }
  915. /**
  916. * 生成flag
  917. * @return string
  918. */
  919. protected function buildFlags()
  920. {
  921. if (! $this->flags) {
  922. return '';
  923. }
  924. return ' ' . implode(' ', array_keys($this->flags));
  925. }
  926. /**
  927. * 设置 flag.
  928. * @param string $flag
  929. * @param bool $enable
  930. * @return null
  931. */
  932. protected function setFlag($flag, $enable = true)
  933. {
  934. if ($enable) {
  935. $this->flags[$flag] = true;
  936. } else {
  937. unset($this->flags[$flag]);
  938. }
  939. }
  940. /**
  941. * 重置flag
  942. * @return null
  943. */
  944. protected function resetFlags()
  945. {
  946. $this->flags = array();
  947. }
  948. /**
  949. *
  950. * 添加where语句
  951. * @param string $andor 'AND' or 'OR
  952. * @param array $conditions
  953. * @return self
  954. *
  955. */
  956. protected function addWhere($andor, $conditions)
  957. {
  958. $this->addClauseCondWithBind('where', $andor, $conditions);
  959. return $this;
  960. }
  961. /**
  962. * 添加条件和绑定值
  963. * @param string $clause where 、having等
  964. * @param string $andor AND、OR等
  965. * @param array $conditions
  966. * @return null
  967. */
  968. protected function addClauseCondWithBind($clause, $andor, $conditions)
  969. {
  970. $cond = array_shift($conditions);
  971. $cond = $this->quoteNamesIn($cond);
  972. $bind =& $this->{"bind_{$clause}"};
  973. foreach ($conditions as $value) {
  974. $bind[] = $value;
  975. }
  976. $clause =& $this->$clause;
  977. if ($clause) {
  978. $clause[] = "$andor $cond";
  979. } else {
  980. $clause[] = $cond;
  981. }
  982. }
  983. /**
  984. * 生成where语句
  985. * @return string
  986. */
  987. protected function buildWhere()
  988. {
  989. if (! $this->where) {
  990. return '';
  991. }
  992. return ' WHERE' . $this->indent($this->where);
  993. }
  994. /**
  995. * 增加order by
  996. * @param array $spec The columns and direction to order by.
  997. * @return self
  998. */
  999. protected function addOrderBy(array $spec)
  1000. {
  1001. foreach ($spec as $col) {
  1002. $this->order_by[] = $this->quoteNamesIn($col);
  1003. }
  1004. return $this;
  1005. }
  1006. /**
  1007. * 生成order by 语句
  1008. * @return string
  1009. */
  1010. protected function buildOrderBy()
  1011. {
  1012. if (! $this->order_by) {
  1013. return '';
  1014. }
  1015. if ($this->order_asc)
  1016. {
  1017. return ' ORDER BY' . $this->indentCsv($this->order_by) . ' ASC';
  1018. }
  1019. else
  1020. {
  1021. return ' ORDER BY' . $this->indentCsv($this->order_by) . ' DESC';
  1022. }
  1023. }
  1024. /**
  1025. * 生成limit语句
  1026. * @return string
  1027. */
  1028. protected function buildLimit()
  1029. {
  1030. $has_limit = $this->type == 'DELETE' || $this->type == 'UPDATE';
  1031. $has_offset = $this->type == 'SELECT';
  1032. if ($has_offset && $this->limit) {
  1033. $clause = " LIMIT {$this->limit}";
  1034. if ($this->offset) {
  1035. $clause .= " OFFSET {$this->offset}";
  1036. }
  1037. return $clause;
  1038. } elseif ($has_limit && $this->limit) {
  1039. return " LIMIT {$this->limit}";
  1040. }
  1041. return '';
  1042. }
  1043. /**
  1044. * Quotes
  1045. * @param string $spec
  1046. * @return string|array
  1047. */
  1048. public function quoteName($spec)
  1049. {
  1050. $spec = trim($spec);
  1051. $seps = array(' AS ', ' ', '.');
  1052. foreach ($seps as $sep) {
  1053. $pos = strripos($spec, $sep);
  1054. if ($pos) {
  1055. return $this->quoteNameWithSeparator($spec, $sep, $pos);
  1056. }
  1057. }
  1058. return $this->replaceName($spec);
  1059. }
  1060. /**
  1061. * 指定分隔符的Quotes
  1062. * @param string $spec
  1063. * @param string $sep
  1064. * @param string $pos
  1065. * @return string
  1066. */
  1067. protected function quoteNameWithSeparator($spec, $sep, $pos)
  1068. {
  1069. $len = strlen($sep);
  1070. $part1 = $this->quoteName(substr($spec, 0, $pos));
  1071. $part2 = $this->replaceName(substr($spec, $pos + $len));
  1072. return "{$part1}{$sep}{$part2}";
  1073. }
  1074. /**
  1075. * Quotes "table.col" 格式的字符串
  1076. * @param string $text
  1077. * @return string|array
  1078. */
  1079. public function quoteNamesIn($text)
  1080. {
  1081. $list = $this->getListForQuoteNamesIn($text);
  1082. $last = count($list) - 1;
  1083. $text = null;
  1084. foreach ($list as $key => $val) {
  1085. if (($key+1) % 3) {
  1086. $text .= $this->quoteNamesInLoop($val, $key == $last);
  1087. }
  1088. }
  1089. return $text;
  1090. }
  1091. /**
  1092. * 返回quote元素列表
  1093. * @param string $text
  1094. * @return array
  1095. */
  1096. protected function getListForQuoteNamesIn($text)
  1097. {
  1098. $apos = "'";
  1099. $quot = '"';
  1100. return preg_split(
  1101. "/(($apos+|$quot+|\\$apos+|\\$quot+).*?\\2)/",
  1102. $text,
  1103. -1,
  1104. PREG_SPLIT_DELIM_CAPTURE
  1105. );
  1106. }
  1107. /**
  1108. * 循环quote
  1109. * @param string $val
  1110. * @param bool $is_last
  1111. * @return string
  1112. */
  1113. protected function quoteNamesInLoop($val, $is_last)
  1114. {
  1115. if ($is_last) {
  1116. return $this->replaceNamesAndAliasIn($val);
  1117. }
  1118. return $this->replaceNamesIn($val);
  1119. }
  1120. /**
  1121. *
  1122. * 替换成别名
  1123. * @param string $val
  1124. * @return string
  1125. */
  1126. protected function replaceNamesAndAliasIn($val)
  1127. {
  1128. $quoted = $this->replaceNamesIn($val);
  1129. $pos = strripos($quoted, ' AS ');
  1130. if ($pos) {
  1131. $alias = $this->replaceName(substr($quoted, $pos + 4));
  1132. $quoted = substr($quoted, 0, $pos) . " AS $alias";
  1133. }
  1134. return $quoted;
  1135. }
  1136. /**
  1137. * Quotes name
  1138. * @param string $name
  1139. * @return string
  1140. */
  1141. protected function replaceName($name)
  1142. {
  1143. $name = trim($name);
  1144. if ($name == '*') {
  1145. return $name;
  1146. }
  1147. return '`'. $name.'`';
  1148. }
  1149. /**
  1150. * Quotes
  1151. * @param string $text
  1152. * @return string|array
  1153. */
  1154. protected function replaceNamesIn($text)
  1155. {
  1156. $is_string_literal = strpos($text, "'") !== false
  1157. || strpos($text, '"') !== false;
  1158. if ($is_string_literal) {
  1159. return $text;
  1160. }
  1161. $word = "[a-z_][a-z0-9_]+";
  1162. $find = "/(\\b)($word)\\.($word)(\\b)/i";
  1163. $repl = '$1`$2`.`$3`$4';
  1164. $text = preg_replace($find, $repl, $text);
  1165. return $text;
  1166. }
  1167. // ---------- insert --------------
  1168. /**
  1169. * 设置 `table.column` 与 last-insert-id 的映射
  1170. * @param array $insert_id_names
  1171. */
  1172. public function setLastInsertIdNames(array $last_insert_id_names)
  1173. {
  1174. $this->last_insert_id_names = $last_insert_id_names;
  1175. }
  1176. /**
  1177. * insert into.
  1178. * @param string $into
  1179. * @return self
  1180. */
  1181. public function into($table)
  1182. {
  1183. $this->table = $this->quoteName($table);
  1184. return $this;
  1185. }
  1186. /**
  1187. * 生成INSERT 语句
  1188. * @return string
  1189. */
  1190. protected function buildINSERT()
  1191. {
  1192. return 'INSERT'
  1193. . $this->buildFlags()
  1194. . $this->buildInto()
  1195. . $this->buildValuesForInsert()
  1196. . $this->buildReturning();
  1197. }
  1198. /**
  1199. * 生成 INTO 语句
  1200. * @return string
  1201. */
  1202. protected function buildInto()
  1203. {
  1204. return " INTO " . $this->table;
  1205. }
  1206. /**
  1207. * PDO::lastInsertId()
  1208. * @param string $col
  1209. * @return mixed
  1210. */
  1211. public function getLastInsertIdName($col)
  1212. {
  1213. $key = str_replace('`', '', $this->table) . '.' . $col;
  1214. if (isset($this->last_insert_id_names[$key])) {
  1215. return $this->last_insert_id_names[$key];
  1216. }
  1217. }
  1218. /**
  1219. *
  1220. * 设置一列,如果有第二各参数,则把第二个参数绑定在占位符上
  1221. * @param string $col
  1222. * @param mixed $val
  1223. * @return self
  1224. */
  1225. public function col($col)
  1226. {
  1227. return call_user_func_array(array($this, 'addCol'), func_get_args());
  1228. }
  1229. /**
  1230. * 设置多列
  1231. * @param array $cols
  1232. * @return self
  1233. */
  1234. public function cols(array $cols)
  1235. {
  1236. if($this->type == 'SELECT')
  1237. {
  1238. foreach ($cols as $key => $val)
  1239. {
  1240. $this->addColSELECT($key, $val);
  1241. }
  1242. return $this;
  1243. }
  1244. return $this->addCols($cols);
  1245. }
  1246. /**
  1247. * 直接设置列的值
  1248. * @param string $col
  1249. * @param string $value
  1250. * @return self
  1251. */
  1252. public function set($col, $value)
  1253. {
  1254. return $this->setCol($col, $value);
  1255. }
  1256. /**
  1257. * 为INSERT语句绑定值
  1258. * @return string
  1259. */
  1260. protected function buildValuesForInsert()
  1261. {
  1262. return ' ('.$this->indentCsv(array_keys($this->col_values)).') VALUES (' . $this->indentCsv(array_values($this->col_values)) . ')';
  1263. }
  1264. // ------update-------
  1265. /**
  1266. * 更新哪个表
  1267. * @param string $table
  1268. * @return self
  1269. */
  1270. public function table($table)
  1271. {
  1272. $this->table = $this->quoteName($table);
  1273. return $this;
  1274. }
  1275. /**
  1276. * 生成完整SQL语句
  1277. * @return string
  1278. */
  1279. protected function build()
  1280. {
  1281. switch($this->type)
  1282. {
  1283. case 'DELETE':
  1284. return $this->buildDELETE();
  1285. case 'INSERT':
  1286. return $this->buildINSERT();
  1287. case 'UPDATE':
  1288. return $this->buildUPDATE();
  1289. case 'SELECT':
  1290. return $this->buildSELECT();
  1291. }
  1292. throw new \Exception("type empty");
  1293. }
  1294. /**
  1295. * 生成更新的SQL语句
  1296. */
  1297. protected function buildUPDATE()
  1298. {
  1299. return 'UPDATE'
  1300. . $this->buildFlags()
  1301. . $this->buildTable()
  1302. . $this->buildValuesForUpdate()
  1303. . $this->buildWhere()
  1304. . $this->buildOrderBy()
  1305. . $this->buildLimit()
  1306. . $this->buildReturning();
  1307. }
  1308. /**
  1309. * 哪个表
  1310. * @return null
  1311. */
  1312. protected function buildTable()
  1313. {
  1314. return " {$this->table}";
  1315. }
  1316. /**
  1317. * 为更新语句绑定值
  1318. * @return string
  1319. */
  1320. protected function buildValuesForUpdate()
  1321. {
  1322. $values = array();
  1323. foreach ($this->col_values as $col => $value) {
  1324. $values[] = "{$col} = {$value}";
  1325. }
  1326. return ' SET' . $this->indentCsv($values);
  1327. }
  1328. // ----------Dml---------------
  1329. /**
  1330. * 获取绑定的值
  1331. * @return array
  1332. */
  1333. public function getBindValuesCOMMON()
  1334. {
  1335. $bind_values = $this->bind_values;
  1336. $i = 1;
  1337. foreach ($this->bind_where as $val) {
  1338. $bind_values[$i] = $val;
  1339. $i ++;
  1340. }
  1341. return $bind_values;
  1342. }
  1343. /**
  1344. * 设置列
  1345. * @param string $col
  1346. * @param mixed $val
  1347. * @return self
  1348. */
  1349. protected function addCol($col)
  1350. {
  1351. $key = $this->quoteName($col);
  1352. $this->col_values[$key] = ":$col";
  1353. $args = func_get_args();
  1354. if (count($args) > 1) {
  1355. $this->bindValue($col, $args[1]);
  1356. }
  1357. return $this;
  1358. }
  1359. /**
  1360. * 设置多个列
  1361. * @param array $cols
  1362. * @return self
  1363. */
  1364. protected function addCols(array $cols)
  1365. {
  1366. foreach ($cols as $key => $val) {
  1367. if (is_int($key)) {
  1368. $this->addCol($val);
  1369. } else {
  1370. $this->addCol($key, $val);
  1371. }
  1372. }
  1373. return $this;
  1374. }
  1375. /**
  1376. * 设置单列的值
  1377. * @param string $col .
  1378. * @param string $value
  1379. * @return self
  1380. */
  1381. protected function setCol($col, $value)
  1382. {
  1383. if ($value === null) {
  1384. $value = 'NULL';
  1385. }
  1386. $key = $this->quoteName($col);
  1387. $value = $this->quoteNamesIn($value);
  1388. $this->col_values[$key] = $value;
  1389. return $this;
  1390. }
  1391. /**
  1392. * 增加返回的列
  1393. * @param array $cols
  1394. * @return self
  1395. *
  1396. */
  1397. protected function addReturning(array $cols)
  1398. {
  1399. foreach ($cols as $col) {
  1400. $this->returning[] = $this->quoteNamesIn($col);
  1401. }
  1402. return $this;
  1403. }
  1404. /**
  1405. * 生成 RETURNING 语句
  1406. * @return string
  1407. */
  1408. protected function buildReturning()
  1409. {
  1410. if (! $this->returning) {
  1411. return '';
  1412. }
  1413. return ' RETURNING' . $this->indentCsv($this->returning);
  1414. }
  1415. /**
  1416. * 构造函数
  1417. */
  1418. public function __construct($host, $port, $user, $password, $db_name, $charset = 'utf8')
  1419. {
  1420. $this->settings = array(
  1421. 'host' => $host,
  1422. 'port' => $port,
  1423. 'user' => $user,
  1424. 'password' => $password,
  1425. 'dbname' => $db_name,
  1426. 'charset' => $charset,
  1427. );
  1428. $this->connect();
  1429. }
  1430. /**
  1431. * 创建pdo实例
  1432. */
  1433. protected function connect()
  1434. {
  1435. $dsn = 'mysql:dbname='.$this->settings["dbname"].';host='.$this->settings["host"].';port='.$this->settings['port'];
  1436. $this->pdo = new \PDO($dsn, $this->settings["user"], $this->settings["password"], array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . (!empty($this->settings['charset']) ? $this->settings['charset'] : 'utf8')));
  1437. $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  1438. $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
  1439. }
  1440. /*
  1441. * 关闭连接
  1442. */
  1443. public function closeConnection()
  1444. {
  1445. $this->pdo = null;
  1446. }
  1447. /**
  1448. * 执行
  1449. * @param string $query
  1450. * @param string $parameters
  1451. */
  1452. protected function execute($query,$parameters = "")
  1453. {
  1454. try {
  1455. $this->sQuery = $this->pdo->prepare($query);
  1456. $this->bindMore($parameters);
  1457. if(!empty($this->parameters)) {
  1458. foreach($this->parameters as $param)
  1459. {
  1460. $parameters = explode("\x7F",$param);
  1461. $this->sQuery->bindParam($parameters[0],$parameters[1]);
  1462. }
  1463. }
  1464. $this->succes = $this->sQuery->execute();
  1465. }
  1466. catch(\PDOException $e)
  1467. {
  1468. // 服务端断开时重连一次
  1469. if($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013)
  1470. {
  1471. $this->closeConnection();
  1472. $this->connect();
  1473. try {
  1474. $this->sQuery = $this->pdo->prepare($query);
  1475. $this->bindMore($parameters);
  1476. if(!empty($this->parameters)) {
  1477. foreach($this->parameters as $param)
  1478. {
  1479. $parameters = explode("\x7F",$param);
  1480. $this->sQuery->bindParam($parameters[0],$parameters[1]);
  1481. }
  1482. }
  1483. $this->succes = $this->sQuery->execute();
  1484. }
  1485. catch(\PDOException $ex)
  1486. {
  1487. $this->rollBackTrans();
  1488. throw $ex;
  1489. }
  1490. }
  1491. else
  1492. {
  1493. $this->rollBackTrans();
  1494. throw $e;
  1495. }
  1496. }
  1497. $this->parameters = array();
  1498. }
  1499. /**
  1500. * 绑定
  1501. * @param string $para
  1502. * @param string $value
  1503. */
  1504. public function bind($para, $value)
  1505. {
  1506. if(is_string($para))
  1507. {
  1508. $this->parameters[sizeof($this->parameters)] = ":" . $para . "\x7F" . $value;
  1509. }
  1510. else
  1511. {
  1512. $this->parameters[sizeof($this->parameters)] = $para . "\x7F" . $value;
  1513. }
  1514. }
  1515. /**
  1516. * 绑定多个
  1517. * @param array $parray
  1518. */
  1519. public function bindMore($parray)
  1520. {
  1521. if(empty($this->parameters) && is_array($parray)) {
  1522. $columns = array_keys($parray);
  1523. foreach($columns as $i => &$column) {
  1524. $this->bind($column, $parray[$column]);
  1525. }
  1526. }
  1527. }
  1528. /**
  1529. * 执行SQL
  1530. * @param string $query
  1531. * @param array $params
  1532. * @param int $fetchmode
  1533. * @return mixed
  1534. */
  1535. public function query($query = '',$params = null, $fetchmode = \PDO::FETCH_ASSOC)
  1536. {
  1537. $query = trim($query);
  1538. if(empty($query))
  1539. {
  1540. $query = $this->build();
  1541. if(!$params)
  1542. {
  1543. $params = $this->getBindValues();
  1544. }
  1545. }
  1546. $this->resetAll();
  1547. $this->lastSql = $query;
  1548. $this->execute($query,$params);
  1549. $rawStatement = explode(" ", $query);
  1550. $statement = strtolower(trim($rawStatement[0]));
  1551. if ($statement === 'select' || $statement === 'show') {
  1552. return $this->sQuery->fetchAll($fetchmode);
  1553. }
  1554. elseif ( $statement === 'update' || $statement === 'delete' ) {
  1555. return $this->sQuery->rowCount();
  1556. }
  1557. elseif( $statement === 'insert' ){
  1558. if( $this->sQuery->rowCount() > 0 ){
  1559. return $this->lastInsertId();
  1560. }
  1561. }
  1562. else {
  1563. return NULL;
  1564. }
  1565. }
  1566. /**
  1567. * 返回一列
  1568. * @param string $query
  1569. * @param array $params
  1570. * @return array
  1571. */
  1572. public function column($query = '',$params = null)
  1573. {
  1574. $query = trim($query);
  1575. if(empty($query))
  1576. {
  1577. $query = $this->build();
  1578. if(!$params)
  1579. {
  1580. $params = $this->getBindValues();
  1581. }
  1582. }
  1583. $this->resetAll();
  1584. $this->lastSql = $query;
  1585. $this->execute($query,$params);
  1586. $columns = $this->sQuery->fetchAll(\PDO::FETCH_NUM);
  1587. $column = null;
  1588. foreach($columns as $cells) {
  1589. $column[] = $cells[0];
  1590. }
  1591. return $column;
  1592. }
  1593. /**
  1594. * 返回一行
  1595. * @param string $query
  1596. * @param array $params
  1597. * @param int $fetchmode
  1598. * @return array
  1599. */
  1600. public function row($query = '',$params = null, $fetchmode = \PDO::FETCH_ASSOC)
  1601. {
  1602. $query = trim($query);
  1603. if(empty($query))
  1604. {
  1605. $query = $this->build();
  1606. if(!$params)
  1607. {
  1608. $params = $this->getBindValues();
  1609. }
  1610. }
  1611. $this->resetAll();
  1612. $this->lastSql = $query;
  1613. $this->execute($query,$params);
  1614. return $this->sQuery->fetch($fetchmode);
  1615. }
  1616. /**
  1617. * 返回单个值
  1618. * @param string $query
  1619. * @param array $params
  1620. * @return string
  1621. */
  1622. public function single($query = '',$params = null)
  1623. {
  1624. $query = trim($query);
  1625. if(empty($query))
  1626. {
  1627. $query = $this->build();
  1628. if(!$params)
  1629. {
  1630. $params = $this->getBindValues();
  1631. }
  1632. }
  1633. $this->resetAll();
  1634. $this->lastSql = $query;
  1635. $this->execute($query,$params);
  1636. return $this->sQuery->fetchColumn();
  1637. }
  1638. /**
  1639. * 返回lastInsertId
  1640. * @return string
  1641. */
  1642. public function lastInsertId() {
  1643. return $this->pdo->lastInsertId();
  1644. }
  1645. /**
  1646. * 返回最后一条直行的sql
  1647. * @return string
  1648. */
  1649. public function lastSQL()
  1650. {
  1651. return $this->lastSql;
  1652. }
  1653. /**
  1654. * 开始事务
  1655. */
  1656. public function beginTrans()
  1657. {
  1658. $this->pdo->beginTransaction();
  1659. }
  1660. /**
  1661. * 提交事务
  1662. */
  1663. public function commitTrans()
  1664. {
  1665. $this->pdo->commit();
  1666. }
  1667. /**
  1668. * 事务回滚
  1669. */
  1670. public function rollBackTrans()
  1671. {
  1672. if ($this->pdo->inTransaction())
  1673. {
  1674. $this->pdo->rollBack();
  1675. }
  1676. }
  1677. }