DbConnection.php 39 KB

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