You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2805 lines
62 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Query Builder Class
  41. *
  42. * This is the platform-independent base Query Builder implementation class.
  43. *
  44. * @package CodeIgniter
  45. * @subpackage Drivers
  46. * @category Database
  47. * @author EllisLab Dev Team
  48. * @link https://codeigniter.com/user_guide/database/
  49. */
  50. abstract class CI_DB_query_builder extends CI_DB_driver {
  51. /**
  52. * Return DELETE SQL flag
  53. *
  54. * @var bool
  55. */
  56. protected $return_delete_sql = FALSE;
  57. /**
  58. * Reset DELETE data flag
  59. *
  60. * @var bool
  61. */
  62. protected $reset_delete_data = FALSE;
  63. /**
  64. * QB SELECT data
  65. *
  66. * @var array
  67. */
  68. protected $qb_select = array();
  69. /**
  70. * QB DISTINCT flag
  71. *
  72. * @var bool
  73. */
  74. protected $qb_distinct = FALSE;
  75. /**
  76. * QB FROM data
  77. *
  78. * @var array
  79. */
  80. protected $qb_from = array();
  81. /**
  82. * QB JOIN data
  83. *
  84. * @var array
  85. */
  86. protected $qb_join = array();
  87. /**
  88. * QB WHERE data
  89. *
  90. * @var array
  91. */
  92. protected $qb_where = array();
  93. /**
  94. * QB GROUP BY data
  95. *
  96. * @var array
  97. */
  98. protected $qb_groupby = array();
  99. /**
  100. * QB HAVING data
  101. *
  102. * @var array
  103. */
  104. protected $qb_having = array();
  105. /**
  106. * QB keys
  107. *
  108. * @var array
  109. */
  110. protected $qb_keys = array();
  111. /**
  112. * QB LIMIT data
  113. *
  114. * @var int
  115. */
  116. protected $qb_limit = FALSE;
  117. /**
  118. * QB OFFSET data
  119. *
  120. * @var int
  121. */
  122. protected $qb_offset = FALSE;
  123. /**
  124. * QB ORDER BY data
  125. *
  126. * @var array
  127. */
  128. protected $qb_orderby = array();
  129. /**
  130. * QB data sets
  131. *
  132. * @var array
  133. */
  134. protected $qb_set = array();
  135. /**
  136. * QB data set for update_batch()
  137. *
  138. * @var array
  139. */
  140. protected $qb_set_ub = array();
  141. /**
  142. * QB aliased tables list
  143. *
  144. * @var array
  145. */
  146. protected $qb_aliased_tables = array();
  147. /**
  148. * QB WHERE group started flag
  149. *
  150. * @var bool
  151. */
  152. protected $qb_where_group_started = FALSE;
  153. /**
  154. * QB WHERE group count
  155. *
  156. * @var int
  157. */
  158. protected $qb_where_group_count = 0;
  159. // Query Builder Caching variables
  160. /**
  161. * QB Caching flag
  162. *
  163. * @var bool
  164. */
  165. protected $qb_caching = FALSE;
  166. /**
  167. * QB Cache exists list
  168. *
  169. * @var array
  170. */
  171. protected $qb_cache_exists = array();
  172. /**
  173. * QB Cache SELECT data
  174. *
  175. * @var array
  176. */
  177. protected $qb_cache_select = array();
  178. /**
  179. * QB Cache FROM data
  180. *
  181. * @var array
  182. */
  183. protected $qb_cache_from = array();
  184. /**
  185. * QB Cache JOIN data
  186. *
  187. * @var array
  188. */
  189. protected $qb_cache_join = array();
  190. /**
  191. * QB Cache aliased tables list
  192. *
  193. * @var array
  194. */
  195. protected $qb_cache_aliased_tables = array();
  196. /**
  197. * QB Cache WHERE data
  198. *
  199. * @var array
  200. */
  201. protected $qb_cache_where = array();
  202. /**
  203. * QB Cache GROUP BY data
  204. *
  205. * @var array
  206. */
  207. protected $qb_cache_groupby = array();
  208. /**
  209. * QB Cache HAVING data
  210. *
  211. * @var array
  212. */
  213. protected $qb_cache_having = array();
  214. /**
  215. * QB Cache ORDER BY data
  216. *
  217. * @var array
  218. */
  219. protected $qb_cache_orderby = array();
  220. /**
  221. * QB Cache data sets
  222. *
  223. * @var array
  224. */
  225. protected $qb_cache_set = array();
  226. /**
  227. * QB No Escape data
  228. *
  229. * @var array
  230. */
  231. protected $qb_no_escape = array();
  232. /**
  233. * QB Cache No Escape data
  234. *
  235. * @var array
  236. */
  237. protected $qb_cache_no_escape = array();
  238. // --------------------------------------------------------------------
  239. /**
  240. * Select
  241. *
  242. * Generates the SELECT portion of the query
  243. *
  244. * @param string
  245. * @param mixed
  246. * @return CI_DB_query_builder
  247. */
  248. public function select($select = '*', $escape = NULL)
  249. {
  250. if (is_string($select))
  251. {
  252. $select = explode(',', $select);
  253. }
  254. // If the escape value was not set, we will base it on the global setting
  255. is_bool($escape) OR $escape = $this->_protect_identifiers;
  256. foreach ($select as $val)
  257. {
  258. $val = trim($val);
  259. if ($val !== '')
  260. {
  261. $this->qb_select[] = $val;
  262. $this->qb_no_escape[] = $escape;
  263. if ($this->qb_caching === TRUE)
  264. {
  265. $this->qb_cache_select[] = $val;
  266. $this->qb_cache_exists[] = 'select';
  267. $this->qb_cache_no_escape[] = $escape;
  268. }
  269. }
  270. }
  271. return $this;
  272. }
  273. // --------------------------------------------------------------------
  274. /**
  275. * Select Max
  276. *
  277. * Generates a SELECT MAX(field) portion of a query
  278. *
  279. * @param string the field
  280. * @param string an alias
  281. * @return CI_DB_query_builder
  282. */
  283. public function select_max($select = '', $alias = '')
  284. {
  285. return $this->_max_min_avg_sum($select, $alias, 'MAX');
  286. }
  287. // --------------------------------------------------------------------
  288. /**
  289. * Select Min
  290. *
  291. * Generates a SELECT MIN(field) portion of a query
  292. *
  293. * @param string the field
  294. * @param string an alias
  295. * @return CI_DB_query_builder
  296. */
  297. public function select_min($select = '', $alias = '')
  298. {
  299. return $this->_max_min_avg_sum($select, $alias, 'MIN');
  300. }
  301. // --------------------------------------------------------------------
  302. /**
  303. * Select Average
  304. *
  305. * Generates a SELECT AVG(field) portion of a query
  306. *
  307. * @param string the field
  308. * @param string an alias
  309. * @return CI_DB_query_builder
  310. */
  311. public function select_avg($select = '', $alias = '')
  312. {
  313. return $this->_max_min_avg_sum($select, $alias, 'AVG');
  314. }
  315. // --------------------------------------------------------------------
  316. /**
  317. * Select Sum
  318. *
  319. * Generates a SELECT SUM(field) portion of a query
  320. *
  321. * @param string the field
  322. * @param string an alias
  323. * @return CI_DB_query_builder
  324. */
  325. public function select_sum($select = '', $alias = '')
  326. {
  327. return $this->_max_min_avg_sum($select, $alias, 'SUM');
  328. }
  329. // --------------------------------------------------------------------
  330. /**
  331. * SELECT [MAX|MIN|AVG|SUM]()
  332. *
  333. * @used-by select_max()
  334. * @used-by select_min()
  335. * @used-by select_avg()
  336. * @used-by select_sum()
  337. *
  338. * @param string $select Field name
  339. * @param string $alias
  340. * @param string $type
  341. * @return CI_DB_query_builder
  342. */
  343. protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX')
  344. {
  345. if ( ! is_string($select) OR $select === '')
  346. {
  347. $this->display_error('db_invalid_query');
  348. }
  349. $type = strtoupper($type);
  350. if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM')))
  351. {
  352. show_error('Invalid function type: '.$type);
  353. }
  354. if ($alias === '')
  355. {
  356. $alias = $this->_create_alias_from_table(trim($select));
  357. }
  358. $sql = $type.'('.$this->protect_identifiers(trim($select)).') AS '.$this->escape_identifiers(trim($alias));
  359. $this->qb_select[] = $sql;
  360. $this->qb_no_escape[] = NULL;
  361. if ($this->qb_caching === TRUE)
  362. {
  363. $this->qb_cache_select[] = $sql;
  364. $this->qb_cache_exists[] = 'select';
  365. }
  366. return $this;
  367. }
  368. // --------------------------------------------------------------------
  369. /**
  370. * Determines the alias name based on the table
  371. *
  372. * @param string $item
  373. * @return string
  374. */
  375. protected function _create_alias_from_table($item)
  376. {
  377. if (strpos($item, '.') !== FALSE)
  378. {
  379. $item = explode('.', $item);
  380. return end($item);
  381. }
  382. return $item;
  383. }
  384. // --------------------------------------------------------------------
  385. /**
  386. * DISTINCT
  387. *
  388. * Sets a flag which tells the query string compiler to add DISTINCT
  389. *
  390. * @param bool $val
  391. * @return CI_DB_query_builder
  392. */
  393. public function distinct($val = TRUE)
  394. {
  395. $this->qb_distinct = is_bool($val) ? $val : TRUE;
  396. return $this;
  397. }
  398. // --------------------------------------------------------------------
  399. /**
  400. * From
  401. *
  402. * Generates the FROM portion of the query
  403. *
  404. * @param mixed $from can be a string or array
  405. * @return CI_DB_query_builder
  406. */
  407. public function from($from)
  408. {
  409. foreach ((array) $from as $val)
  410. {
  411. if (strpos($val, ',') !== FALSE)
  412. {
  413. foreach (explode(',', $val) as $v)
  414. {
  415. $v = trim($v);
  416. $this->_track_aliases($v);
  417. $this->qb_from[] = $v = $this->protect_identifiers($v, TRUE, NULL, FALSE);
  418. if ($this->qb_caching === TRUE)
  419. {
  420. $this->qb_cache_from[] = $v;
  421. $this->qb_cache_exists[] = 'from';
  422. }
  423. }
  424. }
  425. else
  426. {
  427. $val = trim($val);
  428. // Extract any aliases that might exist. We use this information
  429. // in the protect_identifiers to know whether to add a table prefix
  430. $this->_track_aliases($val);
  431. $this->qb_from[] = $val = $this->protect_identifiers($val, TRUE, NULL, FALSE);
  432. if ($this->qb_caching === TRUE)
  433. {
  434. $this->qb_cache_from[] = $val;
  435. $this->qb_cache_exists[] = 'from';
  436. }
  437. }
  438. }
  439. return $this;
  440. }
  441. // --------------------------------------------------------------------
  442. /**
  443. * JOIN
  444. *
  445. * Generates the JOIN portion of the query
  446. *
  447. * @param string
  448. * @param string the join condition
  449. * @param string the type of join
  450. * @param string whether not to try to escape identifiers
  451. * @return CI_DB_query_builder
  452. */
  453. public function join($table, $cond, $type = '', $escape = NULL)
  454. {
  455. if ($type !== '')
  456. {
  457. $type = strtoupper(trim($type));
  458. if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'), TRUE))
  459. {
  460. $type = '';
  461. }
  462. else
  463. {
  464. $type .= ' ';
  465. }
  466. }
  467. // Extract any aliases that might exist. We use this information
  468. // in the protect_identifiers to know whether to add a table prefix
  469. $this->_track_aliases($table);
  470. is_bool($escape) OR $escape = $this->_protect_identifiers;
  471. if ( ! $this->_has_operator($cond))
  472. {
  473. $cond = ' USING ('.($escape ? $this->escape_identifiers($cond) : $cond).')';
  474. }
  475. elseif ($escape === FALSE)
  476. {
  477. $cond = ' ON '.$cond;
  478. }
  479. else
  480. {
  481. // Split multiple conditions
  482. if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE))
  483. {
  484. $conditions = array();
  485. $joints = $joints[0];
  486. array_unshift($joints, array('', 0));
  487. for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i--)
  488. {
  489. $joints[$i][1] += strlen($joints[$i][0]); // offset
  490. $conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]);
  491. $pos = $joints[$i][1] - strlen($joints[$i][0]);
  492. $joints[$i] = $joints[$i][0];
  493. }
  494. }
  495. else
  496. {
  497. $conditions = array($cond);
  498. $joints = array('');
  499. }
  500. $cond = ' ON ';
  501. for ($i = 0, $c = count($conditions); $i < $c; $i++)
  502. {
  503. $operator = $this->_get_operator($conditions[$i]);
  504. $cond .= $joints[$i];
  505. $cond .= preg_match("/(\(*)?([\[\]\w\.'-]+)".preg_quote($operator)."(.*)/i", $conditions[$i], $match)
  506. ? $match[1].$this->protect_identifiers($match[2]).$operator.$this->protect_identifiers($match[3])
  507. : $conditions[$i];
  508. }
  509. }
  510. // Do we want to escape the table name?
  511. if ($escape === TRUE)
  512. {
  513. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  514. }
  515. // Assemble the JOIN statement
  516. $this->qb_join[] = $join = $type.'JOIN '.$table.$cond;
  517. if ($this->qb_caching === TRUE)
  518. {
  519. $this->qb_cache_join[] = $join;
  520. $this->qb_cache_exists[] = 'join';
  521. }
  522. return $this;
  523. }
  524. // --------------------------------------------------------------------
  525. /**
  526. * WHERE
  527. *
  528. * Generates the WHERE portion of the query.
  529. * Separates multiple calls with 'AND'.
  530. *
  531. * @param mixed
  532. * @param mixed
  533. * @param bool
  534. * @return CI_DB_query_builder
  535. */
  536. public function where($key, $value = NULL, $escape = NULL)
  537. {
  538. return $this->_wh('qb_where', $key, $value, 'AND ', $escape);
  539. }
  540. // --------------------------------------------------------------------
  541. /**
  542. * OR WHERE
  543. *
  544. * Generates the WHERE portion of the query.
  545. * Separates multiple calls with 'OR'.
  546. *
  547. * @param mixed
  548. * @param mixed
  549. * @param bool
  550. * @return CI_DB_query_builder
  551. */
  552. public function or_where($key, $value = NULL, $escape = NULL)
  553. {
  554. return $this->_wh('qb_where', $key, $value, 'OR ', $escape);
  555. }
  556. // --------------------------------------------------------------------
  557. /**
  558. * WHERE, HAVING
  559. *
  560. * @used-by where()
  561. * @used-by or_where()
  562. * @used-by having()
  563. * @used-by or_having()
  564. *
  565. * @param string $qb_key 'qb_where' or 'qb_having'
  566. * @param mixed $key
  567. * @param mixed $value
  568. * @param string $type
  569. * @param bool $escape
  570. * @return CI_DB_query_builder
  571. */
  572. protected function _wh($qb_key, $key, $value = NULL, $type = 'AND ', $escape = NULL)
  573. {
  574. $qb_cache_key = ($qb_key === 'qb_having') ? 'qb_cache_having' : 'qb_cache_where';
  575. if ( ! is_array($key))
  576. {
  577. $key = array($key => $value);
  578. }
  579. // If the escape value was not set will base it on the global setting
  580. is_bool($escape) OR $escape = $this->_protect_identifiers;
  581. foreach ($key as $k => $v)
  582. {
  583. $prefix = (count($this->$qb_key) === 0 && count($this->$qb_cache_key) === 0)
  584. ? $this->_group_get_type('')
  585. : $this->_group_get_type($type);
  586. if ($v !== NULL)
  587. {
  588. if ($escape === TRUE)
  589. {
  590. $v = ' '.$this->escape($v);
  591. }
  592. if ( ! $this->_has_operator($k))
  593. {
  594. $k .= ' = ';
  595. }
  596. }
  597. elseif ( ! $this->_has_operator($k))
  598. {
  599. // value appears not to have been set, assign the test to IS NULL
  600. $k .= ' IS NULL';
  601. }
  602. elseif (preg_match('/\s*(!?=|<>|\sIS(?:\s+NOT)?\s)\s*$/i', $k, $match, PREG_OFFSET_CAPTURE))
  603. {
  604. $k = substr($k, 0, $match[0][1]).($match[1][0] === '=' ? ' IS NULL' : ' IS NOT NULL');
  605. }
  606. $this->{$qb_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape);
  607. if ($this->qb_caching === TRUE)
  608. {
  609. $this->{$qb_cache_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape);
  610. $this->qb_cache_exists[] = substr($qb_key, 3);
  611. }
  612. }
  613. return $this;
  614. }
  615. // --------------------------------------------------------------------
  616. /**
  617. * WHERE IN
  618. *
  619. * Generates a WHERE field IN('item', 'item') SQL query,
  620. * joined with 'AND' if appropriate.
  621. *
  622. * @param string $key The field to search
  623. * @param array $values The values searched on
  624. * @param bool $escape
  625. * @return CI_DB_query_builder
  626. */
  627. public function where_in($key = NULL, $values = NULL, $escape = NULL)
  628. {
  629. return $this->_where_in($key, $values, FALSE, 'AND ', $escape);
  630. }
  631. // --------------------------------------------------------------------
  632. /**
  633. * OR WHERE IN
  634. *
  635. * Generates a WHERE field IN('item', 'item') SQL query,
  636. * joined with 'OR' if appropriate.
  637. *
  638. * @param string $key The field to search
  639. * @param array $values The values searched on
  640. * @param bool $escape
  641. * @return CI_DB_query_builder
  642. */
  643. public function or_where_in($key = NULL, $values = NULL, $escape = NULL)
  644. {
  645. return $this->_where_in($key, $values, FALSE, 'OR ', $escape);
  646. }
  647. // --------------------------------------------------------------------
  648. /**
  649. * WHERE NOT IN
  650. *
  651. * Generates a WHERE field NOT IN('item', 'item') SQL query,
  652. * joined with 'AND' if appropriate.
  653. *
  654. * @param string $key The field to search
  655. * @param array $values The values searched on
  656. * @param bool $escape
  657. * @return CI_DB_query_builder
  658. */
  659. public function where_not_in($key = NULL, $values = NULL, $escape = NULL)
  660. {
  661. return $this->_where_in($key, $values, TRUE, 'AND ', $escape);
  662. }
  663. // --------------------------------------------------------------------
  664. /**
  665. * OR WHERE NOT IN
  666. *
  667. * Generates a WHERE field NOT IN('item', 'item') SQL query,
  668. * joined with 'OR' if appropriate.
  669. *
  670. * @param string $key The field to search
  671. * @param array $values The values searched on
  672. * @param bool $escape
  673. * @return CI_DB_query_builder
  674. */
  675. public function or_where_not_in($key = NULL, $values = NULL, $escape = NULL)
  676. {
  677. return $this->_where_in($key, $values, TRUE, 'OR ', $escape);
  678. }
  679. // --------------------------------------------------------------------
  680. /**
  681. * Internal WHERE IN
  682. *
  683. * @used-by where_in()
  684. * @used-by or_where_in()
  685. * @used-by where_not_in()
  686. * @used-by or_where_not_in()
  687. *
  688. * @param string $key The field to search
  689. * @param array $values The values searched on
  690. * @param bool $not If the statement would be IN or NOT IN
  691. * @param string $type
  692. * @param bool $escape
  693. * @return CI_DB_query_builder
  694. */
  695. protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ', $escape = NULL)
  696. {
  697. if ($key === NULL OR $values === NULL)
  698. {
  699. return $this;
  700. }
  701. if ( ! is_array($values))
  702. {
  703. $values = array($values);
  704. }
  705. is_bool($escape) OR $escape = $this->_protect_identifiers;
  706. $not = ($not) ? ' NOT' : '';
  707. if ($escape === TRUE)
  708. {
  709. $where_in = array();
  710. foreach ($values as $value)
  711. {
  712. $where_in[] = $this->escape($value);
  713. }
  714. }
  715. else
  716. {
  717. $where_in = array_values($values);
  718. }
  719. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0)
  720. ? $this->_group_get_type('')
  721. : $this->_group_get_type($type);
  722. $where_in = array(
  723. 'condition' => $prefix.$key.$not.' IN('.implode(', ', $where_in).')',
  724. 'escape' => $escape
  725. );
  726. $this->qb_where[] = $where_in;
  727. if ($this->qb_caching === TRUE)
  728. {
  729. $this->qb_cache_where[] = $where_in;
  730. $this->qb_cache_exists[] = 'where';
  731. }
  732. return $this;
  733. }
  734. // --------------------------------------------------------------------
  735. /**
  736. * LIKE
  737. *
  738. * Generates a %LIKE% portion of the query.
  739. * Separates multiple calls with 'AND'.
  740. *
  741. * @param mixed $field
  742. * @param string $match
  743. * @param string $side
  744. * @param bool $escape
  745. * @return CI_DB_query_builder
  746. */
  747. public function like($field, $match = '', $side = 'both', $escape = NULL)
  748. {
  749. return $this->_like($field, $match, 'AND ', $side, '', $escape);
  750. }
  751. // --------------------------------------------------------------------
  752. /**
  753. * NOT LIKE
  754. *
  755. * Generates a NOT LIKE portion of the query.
  756. * Separates multiple calls with 'AND'.
  757. *
  758. * @param mixed $field
  759. * @param string $match
  760. * @param string $side
  761. * @param bool $escape
  762. * @return CI_DB_query_builder
  763. */
  764. public function not_like($field, $match = '', $side = 'both', $escape = NULL)
  765. {
  766. return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape);
  767. }
  768. // --------------------------------------------------------------------
  769. /**
  770. * OR LIKE
  771. *
  772. * Generates a %LIKE% portion of the query.
  773. * Separates multiple calls with 'OR'.
  774. *
  775. * @param mixed $field
  776. * @param string $match
  777. * @param string $side
  778. * @param bool $escape
  779. * @return CI_DB_query_builder
  780. */
  781. public function or_like($field, $match = '', $side = 'both', $escape = NULL)
  782. {
  783. return $this->_like($field, $match, 'OR ', $side, '', $escape);
  784. }
  785. // --------------------------------------------------------------------
  786. /**
  787. * OR NOT LIKE
  788. *
  789. * Generates a NOT LIKE portion of the query.
  790. * Separates multiple calls with 'OR'.
  791. *
  792. * @param mixed $field
  793. * @param string $match
  794. * @param string $side
  795. * @param bool $escape
  796. * @return CI_DB_query_builder
  797. */
  798. public function or_not_like($field, $match = '', $side = 'both', $escape = NULL)
  799. {
  800. return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape);
  801. }
  802. // --------------------------------------------------------------------
  803. /**
  804. * Internal LIKE
  805. *
  806. * @used-by like()
  807. * @used-by or_like()
  808. * @used-by not_like()
  809. * @used-by or_not_like()
  810. *
  811. * @param mixed $field
  812. * @param string $match
  813. * @param string $type
  814. * @param string $side
  815. * @param string $not
  816. * @param bool $escape
  817. * @return CI_DB_query_builder
  818. */
  819. protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $escape = NULL)
  820. {
  821. if ( ! is_array($field))
  822. {
  823. $field = array($field => $match);
  824. }
  825. is_bool($escape) OR $escape = $this->_protect_identifiers;
  826. // lowercase $side in case somebody writes e.g. 'BEFORE' instead of 'before' (doh)
  827. $side = strtolower($side);
  828. foreach ($field as $k => $v)
  829. {
  830. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0)
  831. ? $this->_group_get_type('') : $this->_group_get_type($type);
  832. if ($escape === TRUE)
  833. {
  834. $v = $this->escape_like_str($v);
  835. }
  836. if ($side === 'none')
  837. {
  838. $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}'";
  839. }
  840. elseif ($side === 'before')
  841. {
  842. $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}'";
  843. }
  844. elseif ($side === 'after')
  845. {
  846. $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}%'";
  847. }
  848. else
  849. {
  850. $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}%'";
  851. }
  852. // some platforms require an escape sequence definition for LIKE wildcards
  853. if ($escape === TRUE && $this->_like_escape_str !== '')
  854. {
  855. $like_statement .= sprintf($this->_like_escape_str, $this->_like_escape_chr);
  856. }
  857. $this->qb_where[] = array('condition' => $like_statement, 'escape' => $escape);
  858. if ($this->qb_caching === TRUE)
  859. {
  860. $this->qb_cache_where[] = array('condition' => $like_statement, 'escape' => $escape);
  861. $this->qb_cache_exists[] = 'where';
  862. }
  863. }
  864. return $this;
  865. }
  866. // --------------------------------------------------------------------
  867. /**
  868. * Starts a query group.
  869. *
  870. * @param string $not (Internal use only)
  871. * @param string $type (Internal use only)
  872. * @return CI_DB_query_builder
  873. */
  874. public function group_start($not = '', $type = 'AND ')
  875. {
  876. $type = $this->_group_get_type($type);
  877. $this->qb_where_group_started = TRUE;
  878. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type;
  879. $where = array(
  880. 'condition' => $prefix.$not.str_repeat(' ', ++$this->qb_where_group_count).' (',
  881. 'escape' => FALSE
  882. );
  883. $this->qb_where[] = $where;
  884. if ($this->qb_caching)
  885. {
  886. $this->qb_cache_where[] = $where;
  887. }
  888. return $this;
  889. }
  890. // --------------------------------------------------------------------
  891. /**
  892. * Starts a query group, but ORs the group
  893. *
  894. * @return CI_DB_query_builder
  895. */
  896. public function or_group_start()
  897. {
  898. return $this->group_start('', 'OR ');
  899. }
  900. // --------------------------------------------------------------------
  901. /**
  902. * Starts a query group, but NOTs the group
  903. *
  904. * @return CI_DB_query_builder
  905. */
  906. public function not_group_start()
  907. {
  908. return $this->group_start('NOT ', 'AND ');
  909. }
  910. // --------------------------------------------------------------------
  911. /**
  912. * Starts a query group, but OR NOTs the group
  913. *
  914. * @return CI_DB_query_builder
  915. */
  916. public function or_not_group_start()
  917. {
  918. return $this->group_start('NOT ', 'OR ');
  919. }
  920. // --------------------------------------------------------------------
  921. /**
  922. * Ends a query group
  923. *
  924. * @return CI_DB_query_builder
  925. */
  926. public function group_end()
  927. {
  928. $this->qb_where_group_started = FALSE;
  929. $where = array(
  930. 'condition' => str_repeat(' ', $this->qb_where_group_count--).')',
  931. 'escape' => FALSE
  932. );
  933. $this->qb_where[] = $where;
  934. if ($this->qb_caching)
  935. {
  936. $this->qb_cache_where[] = $where;
  937. }
  938. return $this;
  939. }
  940. // --------------------------------------------------------------------
  941. /**
  942. * Group_get_type
  943. *
  944. * @used-by group_start()
  945. * @used-by _like()
  946. * @used-by _wh()
  947. * @used-by _where_in()
  948. *
  949. * @param string $type
  950. * @return string
  951. */
  952. protected function _group_get_type($type)
  953. {
  954. if ($this->qb_where_group_started)
  955. {
  956. $type = '';
  957. $this->qb_where_group_started = FALSE;
  958. }
  959. return $type;
  960. }
  961. // --------------------------------------------------------------------
  962. /**
  963. * GROUP BY
  964. *
  965. * @param string $by
  966. * @param bool $escape
  967. * @return CI_DB_query_builder
  968. */
  969. public function group_by($by, $escape = NULL)
  970. {
  971. is_bool($escape) OR $escape = $this->_protect_identifiers;
  972. if (is_string($by))
  973. {
  974. $by = ($escape === TRUE)
  975. ? explode(',', $by)
  976. : array($by);
  977. }
  978. foreach ($by as $val)
  979. {
  980. $val = trim($val);
  981. if ($val !== '')
  982. {
  983. $val = array('field' => $val, 'escape' => $escape);
  984. $this->qb_groupby[] = $val;
  985. if ($this->qb_caching === TRUE)
  986. {
  987. $this->qb_cache_groupby[] = $val;
  988. $this->qb_cache_exists[] = 'groupby';
  989. }
  990. }
  991. }
  992. return $this;
  993. }
  994. // --------------------------------------------------------------------
  995. /**
  996. * HAVING
  997. *
  998. * Separates multiple calls with 'AND'.
  999. *
  1000. * @param string $key
  1001. * @param string $value
  1002. * @param bool $escape
  1003. * @return CI_DB_query_builder
  1004. */
  1005. public function having($key, $value = NULL, $escape = NULL)
  1006. {
  1007. return $this->_wh('qb_having', $key, $value, 'AND ', $escape);
  1008. }
  1009. // --------------------------------------------------------------------
  1010. /**
  1011. * OR HAVING
  1012. *
  1013. * Separates multiple calls with 'OR'.
  1014. *
  1015. * @param string $key
  1016. * @param string $value
  1017. * @param bool $escape
  1018. * @return CI_DB_query_builder
  1019. */
  1020. public function or_having($key, $value = NULL, $escape = NULL)
  1021. {
  1022. return $this->_wh('qb_having', $key, $value, 'OR ', $escape);
  1023. }
  1024. // --------------------------------------------------------------------
  1025. /**
  1026. * ORDER BY
  1027. *
  1028. * @param string $orderby
  1029. * @param string $direction ASC, DESC or RANDOM
  1030. * @param bool $escape
  1031. * @return CI_DB_query_builder
  1032. */
  1033. public function order_by($orderby, $direction = '', $escape = NULL)
  1034. {
  1035. $direction = strtoupper(trim($direction));
  1036. if ($direction === 'RANDOM')
  1037. {
  1038. $direction = '';
  1039. // Do we have a seed value?
  1040. $orderby = ctype_digit((string) $orderby)
  1041. ? sprintf($this->_random_keyword[1], $orderby)
  1042. : $this->_random_keyword[0];
  1043. }
  1044. elseif (empty($orderby))
  1045. {
  1046. return $this;
  1047. }
  1048. elseif ($direction !== '')
  1049. {
  1050. $direction = in_array($direction, array('ASC', 'DESC'), TRUE) ? ' '.$direction : '';
  1051. }
  1052. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1053. if ($escape === FALSE)
  1054. {
  1055. $qb_orderby[] = array('field' => $orderby, 'direction' => $direction, 'escape' => FALSE);
  1056. }
  1057. else
  1058. {
  1059. $qb_orderby = array();
  1060. foreach (explode(',', $orderby) as $field)
  1061. {
  1062. $qb_orderby[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE))
  1063. ? array('field' => ltrim(substr($field, 0, $match[0][1])), 'direction' => ' '.$match[1][0], 'escape' => TRUE)
  1064. : array('field' => trim($field), 'direction' => $direction, 'escape' => TRUE);
  1065. }
  1066. }
  1067. $this->qb_orderby = array_merge($this->qb_orderby, $qb_orderby);
  1068. if ($this->qb_caching === TRUE)
  1069. {
  1070. $this->qb_cache_orderby = array_merge($this->qb_cache_orderby, $qb_orderby);
  1071. $this->qb_cache_exists[] = 'orderby';
  1072. }
  1073. return $this;
  1074. }
  1075. // --------------------------------------------------------------------
  1076. /**
  1077. * LIMIT
  1078. *
  1079. * @param int $value LIMIT value
  1080. * @param int $offset OFFSET value
  1081. * @return CI_DB_query_builder
  1082. */
  1083. public function limit($value, $offset = 0)
  1084. {
  1085. is_null($value) OR $this->qb_limit = (int) $value;
  1086. empty($offset) OR $this->qb_offset = (int) $offset;
  1087. return $this;
  1088. }
  1089. // --------------------------------------------------------------------
  1090. /**
  1091. * Sets the OFFSET value
  1092. *
  1093. * @param int $offset OFFSET value
  1094. * @return CI_DB_query_builder
  1095. */
  1096. public function offset($offset)
  1097. {
  1098. empty($offset) OR $this->qb_offset = (int) $offset;
  1099. return $this;
  1100. }
  1101. // --------------------------------------------------------------------
  1102. /**
  1103. * LIMIT string
  1104. *
  1105. * Generates a platform-specific LIMIT clause.
  1106. *
  1107. * @param string $sql SQL Query
  1108. * @return string
  1109. */
  1110. protected function _limit($sql)
  1111. {
  1112. return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').(int) $this->qb_limit;
  1113. }
  1114. // --------------------------------------------------------------------
  1115. /**
  1116. * The "set" function.
  1117. *
  1118. * Allows key/value pairs to be set for inserting or updating
  1119. *
  1120. * @param mixed
  1121. * @param string
  1122. * @param bool
  1123. * @return CI_DB_query_builder
  1124. */
  1125. public function set($key, $value = '', $escape = NULL)
  1126. {
  1127. $key = $this->_object_to_array($key);
  1128. if ( ! is_array($key))
  1129. {
  1130. $key = array($key => $value);
  1131. }
  1132. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1133. foreach ($key as $k => $v)
  1134. {
  1135. $this->qb_set[$this->protect_identifiers($k, FALSE, $escape)] = ($escape)
  1136. ? $this->escape($v) : $v;
  1137. }
  1138. return $this;
  1139. }
  1140. // --------------------------------------------------------------------
  1141. /**
  1142. * Get SELECT query string
  1143. *
  1144. * Compiles a SELECT query string and returns the sql.
  1145. *
  1146. * @param string the table name to select from (optional)
  1147. * @param bool TRUE: resets QB values; FALSE: leave QB values alone
  1148. * @return string
  1149. */
  1150. public function get_compiled_select($table = '', $reset = TRUE)
  1151. {
  1152. if ($table !== '')
  1153. {
  1154. $this->_track_aliases($table);
  1155. $this->from($table);
  1156. }
  1157. $select = $this->_compile_select();
  1158. if ($reset === TRUE)
  1159. {
  1160. $this->_reset_select();
  1161. }
  1162. return $select;
  1163. }
  1164. // --------------------------------------------------------------------
  1165. /**
  1166. * Get
  1167. *
  1168. * Compiles the select statement based on the other functions called
  1169. * and runs the query
  1170. *
  1171. * @param string the table
  1172. * @param string the limit clause
  1173. * @param string the offset clause
  1174. * @return CI_DB_result
  1175. */
  1176. public function get($table = '', $limit = NULL, $offset = NULL)
  1177. {
  1178. if ($table !== '')
  1179. {
  1180. $this->_track_aliases($table);
  1181. $this->from($table);
  1182. }
  1183. if ( ! empty($limit))
  1184. {
  1185. $this->limit($limit, $offset);
  1186. }
  1187. $result = $this->query($this->_compile_select());
  1188. $this->_reset_select();
  1189. return $result;
  1190. }
  1191. // --------------------------------------------------------------------
  1192. /**
  1193. * "Count All Results" query
  1194. *
  1195. * Generates a platform-specific query string that counts all records
  1196. * returned by an Query Builder query.
  1197. *
  1198. * @param string
  1199. * @param bool the reset clause
  1200. * @return int
  1201. */
  1202. public function count_all_results($table = '', $reset = TRUE)
  1203. {
  1204. if ($table !== '')
  1205. {
  1206. $this->_track_aliases($table);
  1207. $this->from($table);
  1208. }
  1209. // ORDER BY usage is often problematic here (most notably
  1210. // on Microsoft SQL Server) and ultimately unnecessary
  1211. // for selecting COUNT(*) ...
  1212. if ( ! empty($this->qb_orderby))
  1213. {
  1214. $orderby = $this->qb_orderby;
  1215. $this->qb_orderby = NULL;
  1216. }
  1217. $result = ($this->qb_distinct === TRUE OR ! empty($this->qb_groupby) OR ! empty($this->qb_cache_groupby) OR $this->qb_limit OR $this->qb_offset)
  1218. ? $this->query($this->_count_string.$this->protect_identifiers('numrows')."\nFROM (\n".$this->_compile_select()."\n) CI_count_all_results")
  1219. : $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows')));
  1220. if ($reset === TRUE)
  1221. {
  1222. $this->_reset_select();
  1223. }
  1224. // If we've previously reset the qb_orderby values, get them back
  1225. elseif ( ! isset($this->qb_orderby))
  1226. {
  1227. $this->qb_orderby = $orderby;
  1228. }
  1229. if ($result->num_rows() === 0)
  1230. {
  1231. return 0;
  1232. }
  1233. $row = $result->row();
  1234. return (int) $row->numrows;
  1235. }
  1236. // --------------------------------------------------------------------
  1237. /**
  1238. * Get_Where
  1239. *
  1240. * Allows the where clause, limit and offset to be added directly
  1241. *
  1242. * @param string $table
  1243. * @param string $where
  1244. * @param int $limit
  1245. * @param int $offset
  1246. * @return CI_DB_result
  1247. */
  1248. public function get_where($table = '', $where = NULL, $limit = NULL, $offset = NULL)
  1249. {
  1250. if ($table !== '')
  1251. {
  1252. $this->from($table);
  1253. }
  1254. if ($where !== NULL)
  1255. {
  1256. $this->where($where);
  1257. }
  1258. if ( ! empty($limit))
  1259. {
  1260. $this->limit($limit, $offset);
  1261. }
  1262. $result = $this->query($this->_compile_select());
  1263. $this->_reset_select();
  1264. return $result;
  1265. }
  1266. // --------------------------------------------------------------------
  1267. /**
  1268. * Insert_Batch
  1269. *
  1270. * Compiles batch insert strings and runs the queries
  1271. *
  1272. * @param string $table Table to insert into
  1273. * @param array $set An associative array of insert values
  1274. * @param bool $escape Whether to escape values and identifiers
  1275. * @return int Number of rows inserted or FALSE on failure
  1276. */
  1277. public function insert_batch($table, $set = NULL, $escape = NULL, $batch_size = 100)
  1278. {
  1279. if ($set === NULL)
  1280. {
  1281. if (empty($this->qb_set))
  1282. {
  1283. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1284. }
  1285. }
  1286. else
  1287. {
  1288. if (empty($set))
  1289. {
  1290. return ($this->db_debug) ? $this->display_error('insert_batch() called with no data') : FALSE;
  1291. }
  1292. $this->set_insert_batch($set, '', $escape);
  1293. }
  1294. if (strlen($table) === 0)
  1295. {
  1296. if ( ! isset($this->qb_from[0]))
  1297. {
  1298. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1299. }
  1300. $table = $this->qb_from[0];
  1301. }
  1302. // Batch this baby
  1303. $affected_rows = 0;
  1304. for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size)
  1305. {
  1306. if ($this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, $batch_size))))
  1307. {
  1308. $affected_rows += $this->affected_rows();
  1309. }
  1310. }
  1311. $this->_reset_write();
  1312. return $affected_rows;
  1313. }
  1314. // --------------------------------------------------------------------
  1315. /**
  1316. * Insert batch statement
  1317. *
  1318. * Generates a platform-specific insert string from the supplied data.
  1319. *
  1320. * @param string $table Table name
  1321. * @param array $keys INSERT keys
  1322. * @param array $values INSERT values
  1323. * @return string
  1324. */
  1325. protected function _insert_batch($table, $keys, $values)
  1326. {
  1327. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
  1328. }
  1329. // --------------------------------------------------------------------
  1330. /**
  1331. * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts
  1332. *
  1333. * @param mixed
  1334. * @param string
  1335. * @param bool
  1336. * @return CI_DB_query_builder
  1337. */
  1338. public function set_insert_batch($key, $value = '', $escape = NULL)
  1339. {
  1340. $key = $this->_object_to_array_batch($key);
  1341. if ( ! is_array($key))
  1342. {
  1343. $key = array($key => $value);
  1344. }
  1345. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1346. $keys = array_keys($this->_object_to_array(reset($key)));
  1347. sort($keys);
  1348. foreach ($key as $row)
  1349. {
  1350. $row = $this->_object_to_array($row);
  1351. if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0)
  1352. {
  1353. // batch function above returns an error on an empty array
  1354. $this->qb_set[] = array();
  1355. return;
  1356. }
  1357. ksort($row); // puts $row in the same order as our keys
  1358. if ($escape !== FALSE)
  1359. {
  1360. $clean = array();
  1361. foreach ($row as $value)
  1362. {
  1363. $clean[] = $this->escape($value);
  1364. }
  1365. $row = $clean;
  1366. }
  1367. $this->qb_set[] = '('.implode(',', $row).')';
  1368. }
  1369. foreach ($keys as $k)
  1370. {
  1371. $this->qb_keys[] = $this->protect_identifiers($k, FALSE, $escape);
  1372. }
  1373. return $this;
  1374. }
  1375. // --------------------------------------------------------------------
  1376. /**
  1377. * Get INSERT query string
  1378. *
  1379. * Compiles an insert query and returns the sql
  1380. *
  1381. * @param string the table to insert into
  1382. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1383. * @return string
  1384. */
  1385. public function get_compiled_insert($table = '', $reset = TRUE)
  1386. {
  1387. if ($this->_validate_insert($table) === FALSE)
  1388. {
  1389. return FALSE;
  1390. }
  1391. $sql = $this->_insert(
  1392. $this->protect_identifiers(
  1393. $this->qb_from[0], TRUE, NULL, FALSE
  1394. ),
  1395. array_keys($this->qb_set),
  1396. array_values($this->qb_set)
  1397. );
  1398. if ($reset === TRUE)
  1399. {
  1400. $this->_reset_write();
  1401. }
  1402. return $sql;
  1403. }
  1404. // --------------------------------------------------------------------
  1405. /**
  1406. * Insert
  1407. *
  1408. * Compiles an insert string and runs the query
  1409. *
  1410. * @param string the table to insert data into
  1411. * @param array an associative array of insert values
  1412. * @param bool $escape Whether to escape values and identifiers
  1413. * @return bool TRUE on success, FALSE on failure
  1414. */
  1415. public function insert($table = '', $set = NULL, $escape = NULL)
  1416. {
  1417. if ($set !== NULL)
  1418. {
  1419. $this->set($set, '', $escape);
  1420. }
  1421. if ($this->_validate_insert($table) === FALSE)
  1422. {
  1423. return FALSE;
  1424. }
  1425. $sql = $this->_insert(
  1426. $this->protect_identifiers(
  1427. $this->qb_from[0], TRUE, $escape, FALSE
  1428. ),
  1429. array_keys($this->qb_set),
  1430. array_values($this->qb_set)
  1431. );
  1432. $this->_reset_write();
  1433. return $this->query($sql);
  1434. }
  1435. // --------------------------------------------------------------------
  1436. /**
  1437. * Validate Insert
  1438. *
  1439. * This method is used by both insert() and get_compiled_insert() to
  1440. * validate that the there data is actually being set and that table
  1441. * has been chosen to be inserted into.
  1442. *
  1443. * @param string the table to insert data into
  1444. * @return string
  1445. */
  1446. protected function _validate_insert($table = '')
  1447. {
  1448. if (count($this->qb_set) === 0)
  1449. {
  1450. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1451. }
  1452. if ($table !== '')
  1453. {
  1454. $this->qb_from[0] = $table;
  1455. }
  1456. elseif ( ! isset($this->qb_from[0]))
  1457. {
  1458. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1459. }
  1460. return TRUE;
  1461. }
  1462. // --------------------------------------------------------------------
  1463. /**
  1464. * Replace
  1465. *
  1466. * Compiles an replace into string and runs the query
  1467. *
  1468. * @param string the table to replace data into
  1469. * @param array an associative array of insert values
  1470. * @return bool TRUE on success, FALSE on failure
  1471. */
  1472. public function replace($table = '', $set = NULL)
  1473. {
  1474. if ($set !== NULL)
  1475. {
  1476. $this->set($set);
  1477. }
  1478. if (count($this->qb_set) === 0)
  1479. {
  1480. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1481. }
  1482. if ($table === '')
  1483. {
  1484. if ( ! isset($this->qb_from[0]))
  1485. {
  1486. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1487. }
  1488. $table = $this->qb_from[0];
  1489. }
  1490. $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->qb_set), array_values($this->qb_set));
  1491. $this->_reset_write();
  1492. return $this->query($sql);
  1493. }
  1494. // --------------------------------------------------------------------
  1495. /**
  1496. * Replace statement
  1497. *
  1498. * Generates a platform-specific replace string from the supplied data
  1499. *
  1500. * @param string the table name
  1501. * @param array the insert keys
  1502. * @param array the insert values
  1503. * @return string
  1504. */
  1505. protected function _replace($table, $keys, $values)
  1506. {
  1507. return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1508. }
  1509. // --------------------------------------------------------------------
  1510. /**
  1511. * FROM tables
  1512. *
  1513. * Groups tables in FROM clauses if needed, so there is no confusion
  1514. * about operator precedence.
  1515. *
  1516. * Note: This is only used (and overridden) by MySQL and CUBRID.
  1517. *
  1518. * @return string
  1519. */
  1520. protected function _from_tables()
  1521. {
  1522. return implode(', ', $this->qb_from);
  1523. }
  1524. // --------------------------------------------------------------------
  1525. /**
  1526. * Get UPDATE query string
  1527. *
  1528. * Compiles an update query and returns the sql
  1529. *
  1530. * @param string the table to update
  1531. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1532. * @return string
  1533. */
  1534. public function get_compiled_update($table = '', $reset = TRUE)
  1535. {
  1536. // Combine any cached components with the current statements
  1537. $this->_merge_cache();
  1538. if ($this->_validate_update($table) === FALSE)
  1539. {
  1540. return FALSE;
  1541. }
  1542. $sql = $this->_update($this->qb_from[0], $this->qb_set);
  1543. if ($reset === TRUE)
  1544. {
  1545. $this->_reset_write();
  1546. }
  1547. return $sql;
  1548. }
  1549. // --------------------------------------------------------------------
  1550. /**
  1551. * UPDATE
  1552. *
  1553. * Compiles an update string and runs the query.
  1554. *
  1555. * @param string $table
  1556. * @param array $set An associative array of update values
  1557. * @param mixed $where
  1558. * @param int $limit
  1559. * @return bool TRUE on success, FALSE on failure
  1560. */
  1561. public function update($table = '', $set = NULL, $where = NULL, $limit = NULL)
  1562. {
  1563. // Combine any cached components with the current statements
  1564. $this->_merge_cache();
  1565. if ($set !== NULL)
  1566. {
  1567. $this->set($set);
  1568. }
  1569. if ($this->_validate_update($table) === FALSE)
  1570. {
  1571. return FALSE;
  1572. }
  1573. if ($where !== NULL)
  1574. {
  1575. $this->where($where);
  1576. }
  1577. if ( ! empty($limit))
  1578. {
  1579. $this->limit($limit);
  1580. }
  1581. $sql = $this->_update($this->qb_from[0], $this->qb_set);
  1582. $this->_reset_write();
  1583. return $this->query($sql);
  1584. }
  1585. // --------------------------------------------------------------------
  1586. /**
  1587. * Validate Update
  1588. *
  1589. * This method is used by both update() and get_compiled_update() to
  1590. * validate that data is actually being set and that a table has been
  1591. * chosen to be update.
  1592. *
  1593. * @param string the table to update data on
  1594. * @return bool
  1595. */
  1596. protected function _validate_update($table)
  1597. {
  1598. if (count($this->qb_set) === 0)
  1599. {
  1600. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1601. }
  1602. if ($table !== '')
  1603. {
  1604. $this->qb_from = array($this->protect_identifiers($table, TRUE, NULL, FALSE));
  1605. }
  1606. elseif ( ! isset($this->qb_from[0]))
  1607. {
  1608. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1609. }
  1610. return TRUE;
  1611. }
  1612. // --------------------------------------------------------------------
  1613. /**
  1614. * Update_Batch
  1615. *
  1616. * Compiles an update string and runs the query
  1617. *
  1618. * @param string the table to retrieve the results from
  1619. * @param array an associative array of update values
  1620. * @param string the where key
  1621. * @return int number of rows affected or FALSE on failure
  1622. */
  1623. public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100)
  1624. {
  1625. // Combine any cached components with the current statements
  1626. $this->_merge_cache();
  1627. if ($index === NULL)
  1628. {
  1629. return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE;
  1630. }
  1631. if ($set === NULL)
  1632. {
  1633. if (empty($this->qb_set_ub))
  1634. {
  1635. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1636. }
  1637. }
  1638. else
  1639. {
  1640. if (empty($set))
  1641. {
  1642. return ($this->db_debug) ? $this->display_error('update_batch() called with no data') : FALSE;
  1643. }
  1644. $this->set_update_batch($set, $index);
  1645. }
  1646. if (strlen($table) === 0)
  1647. {
  1648. if ( ! isset($this->qb_from[0]))
  1649. {
  1650. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1651. }
  1652. $table = $this->qb_from[0];
  1653. }
  1654. // Batch this baby
  1655. $affected_rows = 0;
  1656. for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size)
  1657. {
  1658. if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index)))
  1659. {
  1660. $affected_rows += $this->affected_rows();
  1661. }
  1662. $this->qb_where = array();
  1663. }
  1664. $this->_reset_write();
  1665. return $affected_rows;
  1666. }
  1667. // --------------------------------------------------------------------
  1668. /**
  1669. * Update_Batch statement
  1670. *
  1671. * Generates a platform-specific batch update string from the supplied data
  1672. *
  1673. * @param string $table Table name
  1674. * @param array $values Update data
  1675. * @param string $index WHERE key
  1676. * @return string
  1677. */
  1678. protected function _update_batch($table, $values, $index)
  1679. {
  1680. $ids = array();
  1681. foreach ($values as $key => $val)
  1682. {
  1683. $ids[] = $val[$index]['value'];
  1684. foreach (array_keys($val) as $field)
  1685. {
  1686. if ($field !== $index)
  1687. {
  1688. $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['field'].' = '.$val[$index]['value'].' THEN '.$val[$field]['value'];
  1689. }
  1690. }
  1691. }
  1692. $cases = '';
  1693. foreach ($final as $k => $v)
  1694. {
  1695. $cases .= $k." = CASE \n"
  1696. .implode("\n", $v)."\n"
  1697. .'ELSE '.$k.' END, ';
  1698. }
  1699. $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE);
  1700. return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where');
  1701. }
  1702. // --------------------------------------------------------------------
  1703. /**
  1704. * The "set_update_batch" function. Allows key/value pairs to be set for batch updating
  1705. *
  1706. * @param array
  1707. * @param string
  1708. * @param bool
  1709. * @return CI_DB_query_builder
  1710. */
  1711. public function set_update_batch($key, $index = '', $escape = NULL)
  1712. {
  1713. $key = $this->_object_to_array_batch($key);
  1714. if ( ! is_array($key))
  1715. {
  1716. // @todo error
  1717. }
  1718. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1719. foreach ($key as $k => $v)
  1720. {
  1721. $index_set = FALSE;
  1722. $clean = array();
  1723. foreach ($v as $k2 => $v2)
  1724. {
  1725. if ($k2 === $index)
  1726. {
  1727. $index_set = TRUE;
  1728. }
  1729. $clean[$k2] = array(
  1730. 'field' => $this->protect_identifiers($k2, FALSE, $escape),
  1731. 'value' => ($escape === FALSE ? $v2 : $this->escape($v2))
  1732. );
  1733. }
  1734. if ($index_set === FALSE)
  1735. {
  1736. return $this->display_error('db_batch_missing_index');
  1737. }
  1738. $this->qb_set_ub[] = $clean;
  1739. }
  1740. return $this;
  1741. }
  1742. // --------------------------------------------------------------------
  1743. /**
  1744. * Empty Table
  1745. *
  1746. * Compiles a delete string and runs "DELETE FROM table"
  1747. *
  1748. * @param string the table to empty
  1749. * @return bool TRUE on success, FALSE on failure
  1750. */
  1751. public function empty_table($table = '')
  1752. {
  1753. if ($table === '')
  1754. {
  1755. if ( ! isset($this->qb_from[0]))
  1756. {
  1757. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1758. }
  1759. $table = $this->qb_from[0];
  1760. }
  1761. else
  1762. {
  1763. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1764. }
  1765. $sql = $this->_delete($table);
  1766. $this->_reset_write();
  1767. return $this->query($sql);
  1768. }
  1769. // --------------------------------------------------------------------
  1770. /**
  1771. * Truncate
  1772. *
  1773. * Compiles a truncate string and runs the query
  1774. * If the database does not support the truncate() command
  1775. * This function maps to "DELETE FROM table"
  1776. *
  1777. * @param string the table to truncate
  1778. * @return bool TRUE on success, FALSE on failure
  1779. */
  1780. public function truncate($table = '')
  1781. {
  1782. if ($table === '')
  1783. {
  1784. if ( ! isset($this->qb_from[0]))
  1785. {
  1786. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1787. }
  1788. $table = $this->qb_from[0];
  1789. }
  1790. else
  1791. {
  1792. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1793. }
  1794. $sql = $this->_truncate($table);
  1795. $this->_reset_write();
  1796. return $this->query($sql);
  1797. }
  1798. // --------------------------------------------------------------------
  1799. /**
  1800. * Truncate statement
  1801. *
  1802. * Generates a platform-specific truncate string from the supplied data
  1803. *
  1804. * If the database does not support the truncate() command,
  1805. * then this method maps to 'DELETE FROM table'
  1806. *
  1807. * @param string the table name
  1808. * @return string
  1809. */
  1810. protected function _truncate($table)
  1811. {
  1812. return 'TRUNCATE '.$table;
  1813. }
  1814. // --------------------------------------------------------------------
  1815. /**
  1816. * Get DELETE query string
  1817. *
  1818. * Compiles a delete query string and returns the sql
  1819. *
  1820. * @param string the table to delete from
  1821. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1822. * @return string
  1823. */
  1824. public function get_compiled_delete($table = '', $reset = TRUE)
  1825. {
  1826. $this->return_delete_sql = TRUE;
  1827. $sql = $this->delete($table, '', NULL, $reset);
  1828. $this->return_delete_sql = FALSE;
  1829. return $sql;
  1830. }
  1831. // --------------------------------------------------------------------
  1832. /**
  1833. * Delete
  1834. *
  1835. * Compiles a delete string and runs the query
  1836. *
  1837. * @param mixed the table(s) to delete from. String or array
  1838. * @param mixed the where clause
  1839. * @param mixed the limit clause
  1840. * @param bool
  1841. * @return mixed
  1842. */
  1843. public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE)
  1844. {
  1845. // Combine any cached components with the current statements
  1846. $this->_merge_cache();
  1847. if ($table === '')
  1848. {
  1849. if ( ! isset($this->qb_from[0]))
  1850. {
  1851. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1852. }
  1853. $table = $this->qb_from[0];
  1854. }
  1855. elseif (is_array($table))
  1856. {
  1857. empty($where) && $reset_data = FALSE;
  1858. foreach ($table as $single_table)
  1859. {
  1860. $this->delete($single_table, $where, $limit, $reset_data);
  1861. }
  1862. return;
  1863. }
  1864. else
  1865. {
  1866. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1867. }
  1868. if ($where !== '')
  1869. {
  1870. $this->where($where);
  1871. }
  1872. if ( ! empty($limit))
  1873. {
  1874. $this->limit($limit);
  1875. }
  1876. if (count($this->qb_where) === 0)
  1877. {
  1878. return ($this->db_debug) ? $this->display_error('db_del_must_use_where') : FALSE;
  1879. }
  1880. $sql = $this->_delete($table);
  1881. if ($reset_data)
  1882. {
  1883. $this->_reset_write();
  1884. }
  1885. return ($this->return_delete_sql === TRUE) ? $sql : $this->query($sql);
  1886. }
  1887. // --------------------------------------------------------------------
  1888. /**
  1889. * Delete statement
  1890. *
  1891. * Generates a platform-specific delete string from the supplied data
  1892. *
  1893. * @param string the table name
  1894. * @return string
  1895. */
  1896. protected function _delete($table)
  1897. {
  1898. return 'DELETE FROM '.$table.$this->_compile_wh('qb_where')
  1899. .($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
  1900. }
  1901. // --------------------------------------------------------------------
  1902. /**
  1903. * DB Prefix
  1904. *
  1905. * Prepends a database prefix if one exists in configuration
  1906. *
  1907. * @param string the table
  1908. * @return string
  1909. */
  1910. public function dbprefix($table = '')
  1911. {
  1912. if ($table === '')
  1913. {
  1914. $this->display_error('db_table_name_required');
  1915. }
  1916. return $this->dbprefix.$table;
  1917. }
  1918. // --------------------------------------------------------------------
  1919. /**
  1920. * Set DB Prefix
  1921. *
  1922. * Set's the DB Prefix to something new without needing to reconnect
  1923. *
  1924. * @param string the prefix
  1925. * @return string
  1926. */
  1927. public function set_dbprefix($prefix = '')
  1928. {
  1929. return $this->dbprefix = $prefix;
  1930. }
  1931. // --------------------------------------------------------------------
  1932. /**
  1933. * Track Aliases
  1934. *
  1935. * Used to track SQL statements written with aliased tables.
  1936. *
  1937. * @param string The table to inspect
  1938. * @return string
  1939. */
  1940. protected function _track_aliases($table)
  1941. {
  1942. if (is_array($table))
  1943. {
  1944. foreach ($table as $t)
  1945. {
  1946. $this->_track_aliases($t);
  1947. }
  1948. return;
  1949. }
  1950. // Does the string contain a comma? If so, we need to separate
  1951. // the string into discreet statements
  1952. if (strpos($table, ',') !== FALSE)
  1953. {
  1954. return $this->_track_aliases(explode(',', $table));
  1955. }
  1956. // if a table alias is used we can recognize it by a space
  1957. if (strpos($table, ' ') !== FALSE)
  1958. {
  1959. // if the alias is written with the AS keyword, remove it
  1960. $table = preg_replace('/\s+AS\s+/i', ' ', $table);
  1961. // Grab the alias
  1962. $table = trim(strrchr($table, ' '));
  1963. // Store the alias, if it doesn't already exist
  1964. if ( ! in_array($table, $this->qb_aliased_tables, TRUE))
  1965. {
  1966. $this->qb_aliased_tables[] = $table;
  1967. if ($this->qb_caching === TRUE && ! in_array($table, $this->qb_cache_aliased_tables, TRUE))
  1968. {
  1969. $this->qb_cache_aliased_tables[] = $table;
  1970. $this->qb_cache_exists[] = 'aliased_tables';
  1971. }
  1972. }
  1973. }
  1974. }
  1975. // --------------------------------------------------------------------
  1976. /**
  1977. * Compile the SELECT statement
  1978. *
  1979. * Generates a query string based on which functions were used.
  1980. * Should not be called directly.
  1981. *
  1982. * @param bool $select_override
  1983. * @return string
  1984. */
  1985. protected function _compile_select($select_override = FALSE)
  1986. {
  1987. // Combine any cached components with the current statements
  1988. $this->_merge_cache();
  1989. // Write the "select" portion of the query
  1990. if ($select_override !== FALSE)
  1991. {
  1992. $sql = $select_override;
  1993. }
  1994. else
  1995. {
  1996. $sql = ( ! $this->qb_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';
  1997. if (count($this->qb_select) === 0)
  1998. {
  1999. $sql .= '*';
  2000. }
  2001. else
  2002. {
  2003. // Cycle through the "select" portion of the query and prep each column name.
  2004. // The reason we protect identifiers here rather than in the select() function
  2005. // is because until the user calls the from() function we don't know if there are aliases
  2006. foreach ($this->qb_select as $key => $val)
  2007. {
  2008. $no_escape = isset($this->qb_no_escape[$key]) ? $this->qb_no_escape[$key] : NULL;
  2009. $this->qb_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape);
  2010. }
  2011. $sql .= implode(', ', $this->qb_select);
  2012. }
  2013. }
  2014. // Write the "FROM" portion of the query
  2015. if (count($this->qb_from) > 0)
  2016. {
  2017. $sql .= "\nFROM ".$this->_from_tables();
  2018. }
  2019. // Write the "JOIN" portion of the query
  2020. if (count($this->qb_join) > 0)
  2021. {
  2022. $sql .= "\n".implode("\n", $this->qb_join);
  2023. }
  2024. $sql .= $this->_compile_wh('qb_where')
  2025. .$this->_compile_group_by()
  2026. .$this->_compile_wh('qb_having')
  2027. .$this->_compile_order_by(); // ORDER BY
  2028. // LIMIT
  2029. if ($this->qb_limit OR $this->qb_offset)
  2030. {
  2031. return $this->_limit($sql."\n");
  2032. }
  2033. return $sql;
  2034. }
  2035. // --------------------------------------------------------------------
  2036. /**
  2037. * Compile WHERE, HAVING statements
  2038. *
  2039. * Escapes identifiers in WHERE and HAVING statements at execution time.
  2040. *
  2041. * Required so that aliases are tracked properly, regardless of whether
  2042. * where(), or_where(), having(), or_having are called prior to from(),
  2043. * join() and dbprefix is added only if needed.
  2044. *
  2045. * @param string $qb_key 'qb_where' or 'qb_having'
  2046. * @return string SQL statement
  2047. */
  2048. protected function _compile_wh($qb_key)
  2049. {
  2050. if (count($this->$qb_key) > 0)
  2051. {
  2052. for ($i = 0, $c = count($this->$qb_key); $i < $c; $i++)
  2053. {
  2054. // Is this condition already compiled?
  2055. if (is_string($this->{$qb_key}[$i]))
  2056. {
  2057. continue;
  2058. }
  2059. elseif ($this->{$qb_key}[$i]['escape'] === FALSE)
  2060. {
  2061. $this->{$qb_key}[$i] = $this->{$qb_key}[$i]['condition'];
  2062. continue;
  2063. }
  2064. // Split multiple conditions
  2065. $conditions = preg_split(
  2066. '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i',
  2067. $this->{$qb_key}[$i]['condition'],
  2068. -1,
  2069. PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
  2070. );
  2071. for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci++)
  2072. {
  2073. if (($op = $this->_get_operator($conditions[$ci])) === FALSE
  2074. OR ! preg_match('/^(\(?)(.*)('.preg_quote($op, '/').')\s*(.*(?<!\)))?(\)?)$/i', $conditions[$ci], $matches))
  2075. {
  2076. continue;
  2077. }
  2078. // $matches = array(
  2079. // 0 => '(test <= foo)', /* the whole thing */
  2080. // 1 => '(', /* optional */
  2081. // 2 => 'test', /* the field name */
  2082. // 3 => ' <= ', /* $op */
  2083. // 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */
  2084. // 5 => ')' /* optional */
  2085. // );
  2086. if ( ! empty($matches[4]))
  2087. {
  2088. $this->_is_literal($matches[4]) OR $matches[4] = $this->protect_identifiers(trim($matches[4]));
  2089. $matches[4] = ' '.$matches[4];
  2090. }
  2091. $conditions[$ci] = $matches[1].$this->protect_identifiers(trim($matches[2]))
  2092. .' '.trim($matches[3]).$matches[4].$matches[5];
  2093. }
  2094. $this->{$qb_key}[$i] = implode('', $conditions);
  2095. }
  2096. return ($qb_key === 'qb_having' ? "\nHAVING " : "\nWHERE ")
  2097. .implode("\n", $this->$qb_key);
  2098. }
  2099. return '';
  2100. }
  2101. // --------------------------------------------------------------------
  2102. /**
  2103. * Compile GROUP BY
  2104. *
  2105. * Escapes identifiers in GROUP BY statements at execution time.
  2106. *
  2107. * Required so that aliases are tracked properly, regardless of whether
  2108. * group_by() is called prior to from(), join() and dbprefix is added
  2109. * only if needed.
  2110. *
  2111. * @return string SQL statement
  2112. */
  2113. protected function _compile_group_by()
  2114. {
  2115. if (count($this->qb_groupby) > 0)
  2116. {
  2117. for ($i = 0, $c = count($this->qb_groupby); $i < $c; $i++)
  2118. {
  2119. // Is it already compiled?
  2120. if (is_string($this->qb_groupby[$i]))
  2121. {
  2122. continue;
  2123. }
  2124. $this->qb_groupby[$i] = ($this->qb_groupby[$i]['escape'] === FALSE OR $this->_is_literal($this->qb_groupby[$i]['field']))
  2125. ? $this->qb_groupby[$i]['field']
  2126. : $this->protect_identifiers($this->qb_groupby[$i]['field']);
  2127. }
  2128. return "\nGROUP BY ".implode(', ', $this->qb_groupby);
  2129. }
  2130. return '';
  2131. }
  2132. // --------------------------------------------------------------------
  2133. /**
  2134. * Compile ORDER BY
  2135. *
  2136. * Escapes identifiers in ORDER BY statements at execution time.
  2137. *
  2138. * Required so that aliases are tracked properly, regardless of whether
  2139. * order_by() is called prior to from(), join() and dbprefix is added
  2140. * only if needed.
  2141. *
  2142. * @return string SQL statement
  2143. */
  2144. protected function _compile_order_by()
  2145. {
  2146. if (empty($this->qb_orderby))
  2147. {
  2148. return '';
  2149. }
  2150. for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++)
  2151. {
  2152. if (is_string($this->qb_orderby[$i]))
  2153. {
  2154. continue;
  2155. }
  2156. if ($this->qb_orderby[$i]['escape'] !== FALSE && ! $this->_is_literal($this->qb_orderby[$i]['field']))
  2157. {
  2158. $this->qb_orderby[$i]['field'] = $this->protect_identifiers($this->qb_orderby[$i]['field']);
  2159. }
  2160. $this->qb_orderby[$i] = $this->qb_orderby[$i]['field'].$this->qb_orderby[$i]['direction'];
  2161. }
  2162. return "\nORDER BY ".implode(', ', $this->qb_orderby);
  2163. }
  2164. // --------------------------------------------------------------------
  2165. /**
  2166. * Object to Array
  2167. *
  2168. * Takes an object as input and converts the class variables to array key/vals
  2169. *
  2170. * @param object
  2171. * @return array
  2172. */
  2173. protected function _object_to_array($object)
  2174. {
  2175. if ( ! is_object($object))
  2176. {
  2177. return $object;
  2178. }
  2179. $array = array();
  2180. foreach (get_object_vars($object) as $key => $val)
  2181. {
  2182. // There are some built in keys we need to ignore for this conversion
  2183. if ( ! is_object($val) && ! is_array($val) && $key !== '_parent_name')
  2184. {
  2185. $array[$key] = $val;
  2186. }
  2187. }
  2188. return $array;
  2189. }
  2190. // --------------------------------------------------------------------
  2191. /**
  2192. * Object to Array
  2193. *
  2194. * Takes an object as input and converts the class variables to array key/vals
  2195. *
  2196. * @param object
  2197. * @return array
  2198. */
  2199. protected function _object_to_array_batch($object)
  2200. {
  2201. if ( ! is_object($object))
  2202. {
  2203. return $object;
  2204. }
  2205. $array = array();
  2206. $out = get_object_vars($object);
  2207. $fields = array_keys($out);
  2208. foreach ($fields as $val)
  2209. {
  2210. // There are some built in keys we need to ignore for this conversion
  2211. if ($val !== '_parent_name')
  2212. {
  2213. $i = 0;
  2214. foreach ($out[$val] as $data)
  2215. {
  2216. $array[$i++][$val] = $data;
  2217. }
  2218. }
  2219. }
  2220. return $array;
  2221. }
  2222. // --------------------------------------------------------------------
  2223. /**
  2224. * Start Cache
  2225. *
  2226. * Starts QB caching
  2227. *
  2228. * @return CI_DB_query_builder
  2229. */
  2230. public function start_cache()
  2231. {
  2232. $this->qb_caching = TRUE;
  2233. return $this;
  2234. }
  2235. // --------------------------------------------------------------------
  2236. /**
  2237. * Stop Cache
  2238. *
  2239. * Stops QB caching
  2240. *
  2241. * @return CI_DB_query_builder
  2242. */
  2243. public function stop_cache()
  2244. {
  2245. $this->qb_caching = FALSE;
  2246. return $this;
  2247. }
  2248. // --------------------------------------------------------------------
  2249. /**
  2250. * Flush Cache
  2251. *
  2252. * Empties the QB cache
  2253. *
  2254. * @return CI_DB_query_builder
  2255. */
  2256. public function flush_cache()
  2257. {
  2258. $this->_reset_run(array(
  2259. 'qb_cache_select' => array(),
  2260. 'qb_cache_from' => array(),
  2261. 'qb_cache_join' => array(),
  2262. 'qb_cache_where' => array(),
  2263. 'qb_cache_groupby' => array(),
  2264. 'qb_cache_having' => array(),
  2265. 'qb_cache_orderby' => array(),
  2266. 'qb_cache_set' => array(),
  2267. 'qb_cache_exists' => array(),
  2268. 'qb_cache_no_escape' => array(),
  2269. 'qb_cache_aliased_tables' => array()
  2270. ));
  2271. return $this;
  2272. }
  2273. // --------------------------------------------------------------------
  2274. /**
  2275. * Merge Cache
  2276. *
  2277. * When called, this function merges any cached QB arrays with
  2278. * locally called ones.
  2279. *
  2280. * @return void
  2281. */
  2282. protected function _merge_cache()
  2283. {
  2284. if (count($this->qb_cache_exists) === 0)
  2285. {
  2286. return;
  2287. }
  2288. elseif (in_array('select', $this->qb_cache_exists, TRUE))
  2289. {
  2290. $qb_no_escape = $this->qb_cache_no_escape;
  2291. }
  2292. foreach (array_unique($this->qb_cache_exists) as $val) // select, from, etc.
  2293. {
  2294. $qb_variable = 'qb_'.$val;
  2295. $qb_cache_var = 'qb_cache_'.$val;
  2296. $qb_new = $this->$qb_cache_var;
  2297. for ($i = 0, $c = count($this->$qb_variable); $i < $c; $i++)
  2298. {
  2299. if ( ! in_array($this->{$qb_variable}[$i], $qb_new, TRUE))
  2300. {
  2301. $qb_new[] = $this->{$qb_variable}[$i];
  2302. if ($val === 'select')
  2303. {
  2304. $qb_no_escape[] = $this->qb_no_escape[$i];
  2305. }
  2306. }
  2307. }
  2308. $this->$qb_variable = $qb_new;
  2309. if ($val === 'select')
  2310. {
  2311. $this->qb_no_escape = $qb_no_escape;
  2312. }
  2313. }
  2314. }
  2315. // --------------------------------------------------------------------
  2316. /**
  2317. * Is literal
  2318. *
  2319. * Determines if a string represents a literal value or a field name
  2320. *
  2321. * @param string $str
  2322. * @return bool
  2323. */
  2324. protected function _is_literal($str)
  2325. {
  2326. $str = trim($str);
  2327. if (empty($str) OR ctype_digit($str) OR (string) (float) $str === $str OR in_array(strtoupper($str), array('TRUE', 'FALSE'), TRUE))
  2328. {
  2329. return TRUE;
  2330. }
  2331. static $_str;
  2332. if (empty($_str))
  2333. {
  2334. $_str = ($this->_escape_char !== '"')
  2335. ? array('"', "'") : array("'");
  2336. }
  2337. return in_array($str[0], $_str, TRUE);
  2338. }
  2339. // --------------------------------------------------------------------
  2340. /**
  2341. * Reset Query Builder values.
  2342. *
  2343. * Publicly-visible method to reset the QB values.
  2344. *
  2345. * @return CI_DB_query_builder
  2346. */
  2347. public function reset_query()
  2348. {
  2349. $this->_reset_select();
  2350. $this->_reset_write();
  2351. return $this;
  2352. }
  2353. // --------------------------------------------------------------------
  2354. /**
  2355. * Resets the query builder values. Called by the get() function
  2356. *
  2357. * @param array An array of fields to reset
  2358. * @return void
  2359. */
  2360. protected function _reset_run($qb_reset_items)
  2361. {
  2362. foreach ($qb_reset_items as $item => $default_value)
  2363. {
  2364. $this->$item = $default_value;
  2365. }
  2366. }
  2367. // --------------------------------------------------------------------
  2368. /**
  2369. * Resets the query builder values. Called by the get() function
  2370. *
  2371. * @return void
  2372. */
  2373. protected function _reset_select()
  2374. {
  2375. $this->_reset_run(array(
  2376. 'qb_select' => array(),
  2377. 'qb_from' => array(),
  2378. 'qb_join' => array(),
  2379. 'qb_where' => array(),
  2380. 'qb_groupby' => array(),
  2381. 'qb_having' => array(),
  2382. 'qb_orderby' => array(),
  2383. 'qb_aliased_tables' => array(),
  2384. 'qb_no_escape' => array(),
  2385. 'qb_distinct' => FALSE,
  2386. 'qb_limit' => FALSE,
  2387. 'qb_offset' => FALSE
  2388. ));
  2389. }
  2390. // --------------------------------------------------------------------
  2391. /**
  2392. * Resets the query builder "write" values.
  2393. *
  2394. * Called by the insert() update() insert_batch() update_batch() and delete() functions
  2395. *
  2396. * @return void
  2397. */
  2398. protected function _reset_write()
  2399. {
  2400. $this->_reset_run(array(
  2401. 'qb_set' => array(),
  2402. 'qb_set_ub' => array(),
  2403. 'qb_from' => array(),
  2404. 'qb_join' => array(),
  2405. 'qb_where' => array(),
  2406. 'qb_orderby' => array(),
  2407. 'qb_keys' => array(),
  2408. 'qb_limit' => FALSE
  2409. ));
  2410. }
  2411. }