DbConnection.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  1. <?php
  2. namespace GatewayWorker\Lib;
  3. /**
  4. * 数据库连接类,依赖mysql_pdo扩展
  5. * 在https://github.com/auraphp/Aura.SqlQuery的基础上修改而成
  6. */
  7. class DbConnection
  8. {
  9. /**
  10. * SELECT
  11. * @var array
  12. */
  13. protected $union = array();
  14. /**
  15. * 是否是更新
  16. * @var bool
  17. */
  18. protected $for_update = false;
  19. /**
  20. * 选择的列
  21. * @var array
  22. */
  23. protected $cols = array();
  24. /**
  25. * 从哪些表里面SELECT
  26. * @var array
  27. */
  28. protected $from = array();
  29. /**
  30. * $from 当前的 key
  31. * @var int
  32. */
  33. protected $from_key = -1;
  34. /**
  35. * GROUP BY 的列
  36. * @var array
  37. */
  38. protected $group_by = array();
  39. /**
  40. * HAVING 条件数组.
  41. * @var array
  42. */
  43. protected $having = array();
  44. /**
  45. * HAVING 语句中绑定的值.
  46. * @var array
  47. */
  48. protected $bind_having = array();
  49. /**
  50. * 每页多少条记录
  51. * @var int
  52. */
  53. protected $paging = 10;
  54. /**
  55. * sql中绑定的值
  56. * @var array
  57. */
  58. protected $bind_values = array();
  59. /**
  60. * WHERE 条件.
  61. * @var array
  62. */
  63. protected $where = array();
  64. /**
  65. * WHERE语句绑定的值
  66. * @var array
  67. */
  68. protected $bind_where = array();
  69. /**
  70. * ORDER BY 的列
  71. * @var array
  72. */
  73. protected $order_by = array();
  74. /**
  75. * 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 === 'insert' || $statement === 'update' || $statement === 'delete' ) {
  1524. return $this->sQuery->rowCount();
  1525. }
  1526. else {
  1527. return NULL;
  1528. }
  1529. }
  1530. /**
  1531. * 返回一列
  1532. * @param string $query
  1533. * @param array $params
  1534. * @return array
  1535. */
  1536. public function column($query = '',$params = null)
  1537. {
  1538. $query = trim($query);
  1539. if(empty($query))
  1540. {
  1541. $query = $this->build();
  1542. if(!$params)
  1543. {
  1544. $params = $this->getBindValues();
  1545. }
  1546. }
  1547. $this->resetAll();
  1548. $this->lastSql = $query;
  1549. $this->execute($query,$params);
  1550. $columns = $this->sQuery->fetchAll(\PDO::FETCH_NUM);
  1551. $column = null;
  1552. foreach($columns as $cells) {
  1553. $column[] = $cells[0];
  1554. }
  1555. return $column;
  1556. }
  1557. /**
  1558. * 返回一行
  1559. * @param string $query
  1560. * @param array $params
  1561. * @param int $fetchmode
  1562. * @return array
  1563. */
  1564. public function row($query = '',$params = null, $fetchmode = \PDO::FETCH_ASSOC)
  1565. {
  1566. $query = trim($query);
  1567. if(empty($query))
  1568. {
  1569. $query = $this->build();
  1570. if(!$params)
  1571. {
  1572. $params = $this->getBindValues();
  1573. }
  1574. }
  1575. $this->resetAll();
  1576. $this->lastSql = $query;
  1577. $this->execute($query,$params);
  1578. return $this->sQuery->fetch($fetchmode);
  1579. }
  1580. /**
  1581. * 返回单个值
  1582. * @param string $query
  1583. * @param array $params
  1584. * @return string
  1585. */
  1586. public function single($query = '',$params = null)
  1587. {
  1588. $query = trim($query);
  1589. if(empty($query))
  1590. {
  1591. $query = $this->build();
  1592. if(!$params)
  1593. {
  1594. $params = $this->getBindValues();
  1595. }
  1596. }
  1597. $this->resetAll();
  1598. $this->lastSql = $query;
  1599. $this->execute($query,$params);
  1600. return $this->sQuery->fetchColumn();
  1601. }
  1602. /**
  1603. * 返回lastInsertId
  1604. * @return string
  1605. */
  1606. public function lastInsertId() {
  1607. return $this->pdo->lastInsertId();
  1608. }
  1609. /**
  1610. * 返回最后一条直行的sql
  1611. * @return string
  1612. */
  1613. public function lastSQL()
  1614. {
  1615. return $this->lastSql;
  1616. }
  1617. }