DbConnection.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  1. <?php
  2. namespace GatewayWorker\Lib;
  3. use Exception;
  4. use PDO;
  5. use PDOException;
  6. /**
  7. * 数据库连接类,依赖 PDO_MYSQL 扩展
  8. * 在 https://github.com/auraphp/Aura.SqlQuery 的基础上修改而成
  9. */
  10. class DbConnection
  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 = array($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) {
  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[] = $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) {
  1224. $alias = $this->replaceName(substr($quoted, $pos + 4));
  1225. $quoted = substr($quoted, 0, $pos) . " AS $alias";
  1226. }
  1227. return $quoted;
  1228. }
  1229. /**
  1230. * Quotes name
  1231. *
  1232. * @param string $name
  1233. * @return string
  1234. */
  1235. protected function replaceName($name)
  1236. {
  1237. $name = trim($name);
  1238. if ($name == '*') {
  1239. return $name;
  1240. }
  1241. return '`' . $name . '`';
  1242. }
  1243. /**
  1244. * Quotes
  1245. *
  1246. * @param string $text
  1247. * @return string|array
  1248. */
  1249. protected function replaceNamesIn($text)
  1250. {
  1251. $is_string_literal = strpos($text, "'") !== false
  1252. || strpos($text, '"') !== false;
  1253. if ($is_string_literal) {
  1254. return $text;
  1255. }
  1256. $word = '[a-z_][a-z0-9_]+';
  1257. $find = "/(\\b)($word)\\.($word)(\\b)/i";
  1258. $repl = '$1`$2`.`$3`$4';
  1259. $text = preg_replace($find, $repl, $text);
  1260. return $text;
  1261. }
  1262. // ---------- insert --------------
  1263. /**
  1264. * 设置 `table.column` 与 last-insert-id 的映射
  1265. *
  1266. * @param array $last_insert_id_names
  1267. */
  1268. public function setLastInsertIdNames(array $last_insert_id_names)
  1269. {
  1270. $this->last_insert_id_names = $last_insert_id_names;
  1271. }
  1272. /**
  1273. * insert into.
  1274. *
  1275. * @param string $table
  1276. * @return self
  1277. */
  1278. public function into($table)
  1279. {
  1280. $this->table = $this->quoteName($table);
  1281. return $this;
  1282. }
  1283. /**
  1284. * 生成 INSERT 语句
  1285. *
  1286. * @return string
  1287. */
  1288. protected function buildINSERT()
  1289. {
  1290. return 'INSERT'
  1291. . $this->buildFlags()
  1292. . $this->buildInto()
  1293. . $this->buildValuesForInsert()
  1294. . $this->buildReturning();
  1295. }
  1296. /**
  1297. * 生成 INTO 语句
  1298. *
  1299. * @return string
  1300. */
  1301. protected function buildInto()
  1302. {
  1303. return " INTO " . $this->table;
  1304. }
  1305. /**
  1306. * PDO::lastInsertId()
  1307. *
  1308. * @param string $col
  1309. * @return mixed
  1310. */
  1311. public function getLastInsertIdName($col)
  1312. {
  1313. $key = str_replace('`', '', $this->table) . '.' . $col;
  1314. if (isset($this->last_insert_id_names[$key])) {
  1315. return $this->last_insert_id_names[$key];
  1316. }
  1317. return null;
  1318. }
  1319. /**
  1320. * 设置一列,如果有第二各参数,则把第二个参数绑定在占位符上
  1321. *
  1322. * @param string $col
  1323. * @return self
  1324. */
  1325. public function col($col)
  1326. {
  1327. return call_user_func_array(array($this, 'addCol'), func_get_args());
  1328. }
  1329. /**
  1330. * 设置多列
  1331. *
  1332. * @param array $cols
  1333. * @return self
  1334. */
  1335. public function cols(array $cols)
  1336. {
  1337. if ($this->type == 'SELECT') {
  1338. foreach ($cols as $key => $val) {
  1339. $this->addColSELECT($key, $val);
  1340. }
  1341. return $this;
  1342. }
  1343. return $this->addCols($cols);
  1344. }
  1345. /**
  1346. * 直接设置列的值
  1347. *
  1348. * @param string $col
  1349. * @param string $value
  1350. * @return self
  1351. */
  1352. public function set($col, $value)
  1353. {
  1354. return $this->setCol($col, $value);
  1355. }
  1356. /**
  1357. * 为 INSERT 语句绑定值
  1358. *
  1359. * @return string
  1360. */
  1361. protected function buildValuesForInsert()
  1362. {
  1363. return ' (' . $this->indentCsv(array_keys($this->col_values)) . ') VALUES (' .
  1364. $this->indentCsv(array_values($this->col_values)) . ')';
  1365. }
  1366. // ------update-------
  1367. /**
  1368. * 更新哪个表
  1369. *
  1370. * @param string $table
  1371. * @return self
  1372. */
  1373. public function table($table)
  1374. {
  1375. $this->table = $this->quoteName($table);
  1376. return $this;
  1377. }
  1378. /**
  1379. * 生成完整 SQL 语句
  1380. *
  1381. * @return string
  1382. * @throws Exception
  1383. */
  1384. protected function build()
  1385. {
  1386. switch ($this->type) {
  1387. case 'DELETE':
  1388. return $this->buildDELETE();
  1389. case 'INSERT':
  1390. return $this->buildINSERT();
  1391. case 'UPDATE':
  1392. return $this->buildUPDATE();
  1393. case 'SELECT':
  1394. return $this->buildSELECT();
  1395. }
  1396. throw new Exception("type empty");
  1397. }
  1398. /**
  1399. * 生成更新的 SQL 语句
  1400. */
  1401. protected function buildUPDATE()
  1402. {
  1403. return 'UPDATE'
  1404. . $this->buildFlags()
  1405. . $this->buildTable()
  1406. . $this->buildValuesForUpdate()
  1407. . $this->buildWhere()
  1408. . $this->buildOrderBy()
  1409. . $this->buildLimit()
  1410. . $this->buildReturning();
  1411. }
  1412. /**
  1413. * 哪个表
  1414. *
  1415. * @return string
  1416. */
  1417. protected function buildTable()
  1418. {
  1419. return " {$this->table}";
  1420. }
  1421. /**
  1422. * 为更新语句绑定值
  1423. *
  1424. * @return string
  1425. */
  1426. protected function buildValuesForUpdate()
  1427. {
  1428. $values = array();
  1429. foreach ($this->col_values as $col => $value) {
  1430. $values[] = "{$col} = {$value}";
  1431. }
  1432. return ' SET' . $this->indentCsv($values);
  1433. }
  1434. // ----------Dml---------------
  1435. /**
  1436. * 获取绑定的值
  1437. *
  1438. * @return array
  1439. */
  1440. public function getBindValuesCOMMON()
  1441. {
  1442. $bind_values = $this->bind_values;
  1443. $i = 1;
  1444. foreach ($this->bind_where as $val) {
  1445. $bind_values[$i] = $val;
  1446. $i++;
  1447. }
  1448. return $bind_values;
  1449. }
  1450. /**
  1451. * 设置列
  1452. *
  1453. * @param string $col
  1454. * @return self
  1455. */
  1456. protected function addCol($col)
  1457. {
  1458. $key = $this->quoteName($col);
  1459. $this->col_values[$key] = ":$col";
  1460. $args = func_get_args();
  1461. if (count($args) > 1) {
  1462. $this->bindValue($col, $args[1]);
  1463. }
  1464. return $this;
  1465. }
  1466. /**
  1467. * 设置多个列
  1468. *
  1469. * @param array $cols
  1470. * @return self
  1471. */
  1472. protected function addCols(array $cols)
  1473. {
  1474. foreach ($cols as $key => $val) {
  1475. if (is_int($key)) {
  1476. $this->addCol($val);
  1477. } else {
  1478. $this->addCol($key, $val);
  1479. }
  1480. }
  1481. return $this;
  1482. }
  1483. /**
  1484. * 设置单列的值
  1485. *
  1486. * @param string $col .
  1487. * @param string $value
  1488. * @return self
  1489. */
  1490. protected function setCol($col, $value)
  1491. {
  1492. if ($value === null) {
  1493. $value = 'NULL';
  1494. }
  1495. $key = $this->quoteName($col);
  1496. $value = $this->quoteNamesIn($value);
  1497. $this->col_values[$key] = $value;
  1498. return $this;
  1499. }
  1500. /**
  1501. * 增加返回的列
  1502. *
  1503. * @param array $cols
  1504. * @return self
  1505. *
  1506. */
  1507. protected function addReturning(array $cols)
  1508. {
  1509. foreach ($cols as $col) {
  1510. $this->returning[] = $this->quoteNamesIn($col);
  1511. }
  1512. return $this;
  1513. }
  1514. /**
  1515. * 生成 RETURNING 语句
  1516. *
  1517. * @return string
  1518. */
  1519. protected function buildReturning()
  1520. {
  1521. if (!$this->returning) {
  1522. return '';
  1523. }
  1524. return ' RETURNING' . $this->indentCsv($this->returning);
  1525. }
  1526. /**
  1527. * 构造函数
  1528. *
  1529. * @param string $host
  1530. * @param int $port
  1531. * @param string $user
  1532. * @param string $password
  1533. * @param string $db_name
  1534. * @param string $charset
  1535. */
  1536. public function __construct($config)
  1537. {
  1538. /*$this->settings = array(
  1539. 'host' => $host,
  1540. 'port' => $port,
  1541. 'user' => $user,
  1542. 'password' => $password,
  1543. 'dbname' => $db_name,
  1544. 'charset' => $charset,
  1545. );*/
  1546. $this->settings = $config;
  1547. $this->connect();
  1548. }
  1549. /**
  1550. * 创建 PDO 实例
  1551. */
  1552. protected function connect()
  1553. {
  1554. $dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' .
  1555. $this->settings["host"] . ';port=' . $this->settings['port'];
  1556. $this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"],
  1557. array(
  1558. PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . (!empty($this->settings['charset']) ?
  1559. $this->settings['charset'] : 'utf8')
  1560. ));
  1561. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1562. $this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
  1563. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  1564. }
  1565. /**
  1566. * 关闭连接
  1567. */
  1568. public function closeConnection()
  1569. {
  1570. $this->pdo = null;
  1571. }
  1572. /**
  1573. * 执行
  1574. *
  1575. * @param string $query
  1576. * @param string $parameters
  1577. * @throws PDOException
  1578. */
  1579. protected function execute($query, $parameters = "")
  1580. {
  1581. try {
  1582. $this->sQuery = @$this->pdo->prepare($query);
  1583. $this->bindMore($parameters);
  1584. if (!empty($this->parameters)) {
  1585. foreach ($this->parameters as $param) {
  1586. $parameters = explode("\x7F", $param);
  1587. $this->sQuery->bindParam($parameters[0], $parameters[1]);
  1588. }
  1589. }
  1590. $this->success = $this->sQuery->execute();
  1591. } catch (PDOException $e) {
  1592. // 服务端断开时重连一次
  1593. if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
  1594. $this->closeConnection();
  1595. $this->connect();
  1596. try {
  1597. $this->sQuery = $this->pdo->prepare($query);
  1598. $this->bindMore($parameters);
  1599. if (!empty($this->parameters)) {
  1600. foreach ($this->parameters as $param) {
  1601. $parameters = explode("\x7F", $param);
  1602. $this->sQuery->bindParam($parameters[0], $parameters[1]);
  1603. }
  1604. }
  1605. $this->success = $this->sQuery->execute();
  1606. } catch (PDOException $ex) {
  1607. $this->rollBackTrans();
  1608. throw $ex;
  1609. }
  1610. } else {
  1611. $this->rollBackTrans();
  1612. $msg = $e->getMessage();
  1613. $err_msg = "SQL:".$this->lastSQL()." ".$msg;
  1614. $exception = new \PDOException($err_msg, (int)$e->getCode());
  1615. throw $exception;
  1616. }
  1617. }
  1618. $this->parameters = array();
  1619. }
  1620. /**
  1621. * 绑定
  1622. *
  1623. * @param string $para
  1624. * @param string $value
  1625. */
  1626. public function bind($para, $value)
  1627. {
  1628. if (is_string($para)) {
  1629. $this->parameters[sizeof($this->parameters)] = ":" . $para . "\x7F" . $value;
  1630. } else {
  1631. $this->parameters[sizeof($this->parameters)] = $para . "\x7F" . $value;
  1632. }
  1633. }
  1634. /**
  1635. * 绑定多个
  1636. *
  1637. * @param array $parray
  1638. */
  1639. public function bindMore($parray)
  1640. {
  1641. if (empty($this->parameters) && is_array($parray)) {
  1642. $columns = array_keys($parray);
  1643. foreach ($columns as $i => &$column) {
  1644. $this->bind($column, $parray[$column]);
  1645. }
  1646. }
  1647. }
  1648. /**
  1649. * 执行 SQL
  1650. *
  1651. * @param string $query
  1652. * @param array $params
  1653. * @param int $fetchmode
  1654. * @return mixed
  1655. */
  1656. public function query($query = '', $params = null, $fetchmode = PDO::FETCH_ASSOC)
  1657. {
  1658. $query = trim($query);
  1659. if (empty($query)) {
  1660. $query = $this->build();
  1661. if (!$params) {
  1662. $params = $this->getBindValues();
  1663. }
  1664. }
  1665. $this->resetAll();
  1666. $this->lastSql = $query;
  1667. $this->execute($query, $params);
  1668. $rawStatement = explode(" ", $query);
  1669. $statement = strtolower(trim($rawStatement[0]));
  1670. if ($statement === 'select' || $statement === 'show') {
  1671. return $this->sQuery->fetchAll($fetchmode);
  1672. } elseif ($statement === 'update' || $statement === 'delete') {
  1673. return $this->sQuery->rowCount();
  1674. } elseif ($statement === 'insert') {
  1675. if ($this->sQuery->rowCount() > 0) {
  1676. return $this->lastInsertId();
  1677. }
  1678. } else {
  1679. return null;
  1680. }
  1681. return null;
  1682. }
  1683. /**
  1684. * 返回一列
  1685. *
  1686. * @param string $query
  1687. * @param array $params
  1688. * @return array
  1689. */
  1690. public function column($query = '', $params = null)
  1691. {
  1692. $query = trim($query);
  1693. if (empty($query)) {
  1694. $query = $this->build();
  1695. if (!$params) {
  1696. $params = $this->getBindValues();
  1697. }
  1698. }
  1699. $this->resetAll();
  1700. $this->lastSql = $query;
  1701. $this->execute($query, $params);
  1702. $columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);
  1703. $column = null;
  1704. foreach ($columns as $cells) {
  1705. $column[] = $cells[0];
  1706. }
  1707. return $column;
  1708. }
  1709. /**
  1710. * 返回一行
  1711. *
  1712. * @param string $query
  1713. * @param array $params
  1714. * @param int $fetchmode
  1715. * @return array
  1716. */
  1717. public function row($query = '', $params = null, $fetchmode = PDO::FETCH_ASSOC)
  1718. {
  1719. $query = trim($query);
  1720. if (empty($query)) {
  1721. $query = $this->build();
  1722. if (!$params) {
  1723. $params = $this->getBindValues();
  1724. }
  1725. }
  1726. $this->resetAll();
  1727. $this->lastSql = $query;
  1728. $this->execute($query, $params);
  1729. return $this->sQuery->fetch($fetchmode);
  1730. }
  1731. /**
  1732. * 返回单个值
  1733. *
  1734. * @param string $query
  1735. * @param array $params
  1736. * @return string
  1737. */
  1738. public function single($query = '', $params = null)
  1739. {
  1740. $query = trim($query);
  1741. if (empty($query)) {
  1742. $query = $this->build();
  1743. if (!$params) {
  1744. $params = $this->getBindValues();
  1745. }
  1746. }
  1747. $this->resetAll();
  1748. $this->lastSql = $query;
  1749. $this->execute($query, $params);
  1750. return $this->sQuery->fetchColumn();
  1751. }
  1752. /**
  1753. * 返回 lastInsertId
  1754. *
  1755. * @return string
  1756. */
  1757. public function lastInsertId()
  1758. {
  1759. return $this->pdo->lastInsertId();
  1760. }
  1761. /**
  1762. * 返回最后一条执行的 sql
  1763. *
  1764. * @return string
  1765. */
  1766. public function lastSQL()
  1767. {
  1768. return $this->lastSql;
  1769. }
  1770. /**
  1771. * 开始事务
  1772. */
  1773. public function beginTrans()
  1774. {
  1775. try {
  1776. $this->pdo->beginTransaction();
  1777. } catch (PDOException $e) {
  1778. // 服务端断开时重连一次
  1779. if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
  1780. $this->pdo->beginTransaction();
  1781. } else {
  1782. throw $e;
  1783. }
  1784. }
  1785. }
  1786. /**
  1787. * 提交事务
  1788. */
  1789. public function commitTrans()
  1790. {
  1791. $this->pdo->commit();
  1792. }
  1793. /**
  1794. * 事务回滚
  1795. */
  1796. public function rollBackTrans()
  1797. {
  1798. if ($this->pdo->inTransaction()) {
  1799. $this->pdo->rollBack();
  1800. }
  1801. }
  1802. }