Connection.php 42 KB

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