PageRenderTime 67ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/system/database/DB_driver.php

https://github.com/betchi/CodeIgniter
PHP | 1886 lines | 1124 code | 176 blank | 586 comment | 73 complexity | ffdd01a368d347f6d704fef2b7f95b7c MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.2.4 or newer
  6. *
  7. * NOTICE OF LICENSE
  8. *
  9. * Licensed under the Open Software License version 3.0
  10. *
  11. * This source file is subject to the Open Software License (OSL 3.0) that is
  12. * bundled with this package in the files license.txt / license.rst. It is
  13. * also available through the world wide web at this URL:
  14. * http://opensource.org/licenses/OSL-3.0
  15. * If you did not receive a copy of the license and are unable to obtain it
  16. * through the world wide web, please send an email to
  17. * licensing@ellislab.com so we can send you a copy immediately.
  18. *
  19. * @package CodeIgniter
  20. * @author EllisLab Dev Team
  21. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
  22. * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
  23. * @link http://codeigniter.com
  24. * @since Version 1.0
  25. * @filesource
  26. */
  27. defined('BASEPATH') OR exit('No direct script access allowed');
  28. /**
  29. * Database Driver Class
  30. *
  31. * This is the platform-independent base DB implementation class.
  32. * This class will not be called directly. Rather, the adapter
  33. * class for the specific database will extend and instantiate it.
  34. *
  35. * @package CodeIgniter
  36. * @subpackage Drivers
  37. * @category Database
  38. * @author EllisLab Dev Team
  39. * @link http://codeigniter.com/user_guide/database/
  40. */
  41. abstract class CI_DB_driver {
  42. /**
  43. * Data Source Name / Connect string
  44. *
  45. * @var string
  46. */
  47. public $dsn;
  48. /**
  49. * Username
  50. *
  51. * @var string
  52. */
  53. public $username;
  54. /**
  55. * Password
  56. *
  57. * @var string
  58. */
  59. public $password;
  60. /**
  61. * Hostname
  62. *
  63. * @var string
  64. */
  65. public $hostname;
  66. /**
  67. * Database name
  68. *
  69. * @var string
  70. */
  71. public $database;
  72. /**
  73. * Database driver
  74. *
  75. * @var string
  76. */
  77. public $dbdriver = 'mysqli';
  78. /**
  79. * Sub-driver
  80. *
  81. * @used-by CI_DB_pdo_driver
  82. * @var string
  83. */
  84. public $subdriver;
  85. /**
  86. * Table prefix
  87. *
  88. * @var string
  89. */
  90. public $dbprefix = '';
  91. /**
  92. * Character set
  93. *
  94. * @var string
  95. */
  96. public $char_set = 'utf8';
  97. /**
  98. * Collation
  99. *
  100. * @var string
  101. */
  102. public $dbcollat = 'utf8_general_ci';
  103. /**
  104. * Auto-init flag
  105. *
  106. * Whether to automatically initialize the DB connection.
  107. *
  108. * @var bool
  109. */
  110. public $autoinit = TRUE;
  111. /**
  112. * Encryption flag/data
  113. *
  114. * @var mixed
  115. */
  116. public $encrypt = FALSE;
  117. /**
  118. * Swap Prefix
  119. *
  120. * @var string
  121. */
  122. public $swap_pre = '';
  123. /**
  124. * Database port
  125. *
  126. * @var int
  127. */
  128. public $port = '';
  129. /**
  130. * Persistent connection flag
  131. *
  132. * @var bool
  133. */
  134. public $pconnect = FALSE;
  135. /**
  136. * Connection ID
  137. *
  138. * @var object|resource
  139. */
  140. public $conn_id = FALSE;
  141. /**
  142. * Result ID
  143. *
  144. * @var object|resource
  145. */
  146. public $result_id = FALSE;
  147. /**
  148. * Debug flag
  149. *
  150. * Whether to display error messages.
  151. *
  152. * @var bool
  153. */
  154. public $db_debug = FALSE;
  155. /**
  156. * Benchmark time
  157. *
  158. * @var int
  159. */
  160. public $benchmark = 0;
  161. /**
  162. * Executed queries count
  163. *
  164. * @var int
  165. */
  166. public $query_count = 0;
  167. /**
  168. * Bind marker
  169. *
  170. * Character used to identify values in a prepared statement.
  171. *
  172. * @var string
  173. */
  174. public $bind_marker = '?';
  175. /**
  176. * Save queries flag
  177. *
  178. * Whether to keep an in-memory history of queries for debugging purposes.
  179. *
  180. * @var bool
  181. */
  182. public $save_queries = TRUE;
  183. /**
  184. * Queries list
  185. *
  186. * @see CI_DB_driver::$save_queries
  187. * @var string[]
  188. */
  189. public $queries = array();
  190. /**
  191. * Query times
  192. *
  193. * A list of times that queries took to execute.
  194. *
  195. * @var array
  196. */
  197. public $query_times = array();
  198. /**
  199. * Data cache
  200. *
  201. * An internal generic value cache.
  202. *
  203. * @var array
  204. */
  205. public $data_cache = array();
  206. /**
  207. * Transaction enabled flag
  208. *
  209. * @var bool
  210. */
  211. public $trans_enabled = TRUE;
  212. /**
  213. * Strict transaction mode flag
  214. *
  215. * @var bool
  216. */
  217. public $trans_strict = TRUE;
  218. /**
  219. * Transaction depth level
  220. *
  221. * @var int
  222. */
  223. protected $_trans_depth = 0;
  224. /**
  225. * Transaction status flag
  226. *
  227. * Used with transactions to determine if a rollback should occur.
  228. *
  229. * @var bool
  230. */
  231. protected $_trans_status = TRUE;
  232. /**
  233. * Transaction failure flag
  234. *
  235. * Used with transactions to determine if a transaction has failed.
  236. *
  237. * @var bool
  238. */
  239. protected $_trans_failure = FALSE;
  240. /**
  241. * Cache On flag
  242. *
  243. * @var bool
  244. */
  245. public $cache_on = FALSE;
  246. /**
  247. * Cache directory path
  248. *
  249. * @var bool
  250. */
  251. public $cachedir = '';
  252. /**
  253. * Cache auto-delete flag
  254. *
  255. * @var bool
  256. */
  257. public $cache_autodel = FALSE;
  258. /**
  259. * DB Cache object
  260. *
  261. * @see CI_DB_cache
  262. * @var object
  263. */
  264. public $CACHE;
  265. /**
  266. * Protect identifiers flag
  267. *
  268. * @var bool
  269. */
  270. protected $_protect_identifiers = TRUE;
  271. /**
  272. * List of reserved identifiers
  273. *
  274. * Identifiers that must NOT be escaped.
  275. *
  276. * @var string[]
  277. */
  278. protected $_reserved_identifiers = array('*');
  279. /**
  280. * Identifier escape character
  281. *
  282. * @var string
  283. */
  284. protected $_escape_char = '"';
  285. /**
  286. * ESCAPE statement string
  287. *
  288. * @var string
  289. */
  290. protected $_like_escape_str = " ESCAPE '%s' ";
  291. /**
  292. * ESCAPE character
  293. *
  294. * @var string
  295. */
  296. protected $_like_escape_chr = '!';
  297. /**
  298. * ORDER BY random keyword
  299. *
  300. * @var array
  301. */
  302. protected $_random_keyword = array('RAND()', 'RAND(%d)');
  303. /**
  304. * COUNT string
  305. *
  306. * @used-by CI_DB_driver::count_all()
  307. * @used-by CI_DB_query_builder::count_all_results()
  308. *
  309. * @var string
  310. */
  311. protected $_count_string = 'SELECT COUNT(*) AS ';
  312. // --------------------------------------------------------------------
  313. /**
  314. * Class constructor
  315. *
  316. * @param array $params
  317. * @return void
  318. */
  319. public function __construct($params)
  320. {
  321. if (is_array($params))
  322. {
  323. foreach ($params as $key => $val)
  324. {
  325. $this->$key = $val;
  326. }
  327. }
  328. log_message('debug', 'Database Driver Class Initialized');
  329. }
  330. // --------------------------------------------------------------------
  331. /**
  332. * Initialize Database Settings
  333. *
  334. * @return bool
  335. */
  336. public function initialize()
  337. {
  338. /* If an established connection is available, then there's
  339. * no need to connect and select the database.
  340. *
  341. * Depending on the database driver, conn_id can be either
  342. * boolean TRUE, a resource or an object.
  343. */
  344. if ($this->conn_id)
  345. {
  346. return TRUE;
  347. }
  348. // ----------------------------------------------------------------
  349. // Connect to the database and set the connection ID
  350. $this->conn_id = $this->db_connect($this->pconnect);
  351. // No connection resource? Check if there is a failover else throw an error
  352. if ( ! $this->conn_id)
  353. {
  354. // Check if there is a failover set
  355. if ( ! empty($this->failover) && is_array($this->failover))
  356. {
  357. // Go over all the failovers
  358. foreach ($this->failover as $failover)
  359. {
  360. // Replace the current settings with those of the failover
  361. foreach ($failover as $key => $val)
  362. {
  363. $this->$key = $val;
  364. }
  365. // Try to connect
  366. $this->conn_id = $this->db_connect($this->pconnect);
  367. // If a connection is made break the foreach loop
  368. if ($this->conn_id)
  369. {
  370. break;
  371. }
  372. }
  373. }
  374. // We still don't have a connection?
  375. if ( ! $this->conn_id)
  376. {
  377. log_message('error', 'Unable to connect to the database');
  378. if ($this->db_debug)
  379. {
  380. $this->display_error('db_unable_to_connect');
  381. }
  382. return FALSE;
  383. }
  384. }
  385. // Now we set the character set and that's all
  386. return $this->db_set_charset($this->char_set);
  387. }
  388. // --------------------------------------------------------------------
  389. /**
  390. * Persistent database connection
  391. *
  392. * @return resource
  393. */
  394. public function db_pconnect()
  395. {
  396. return $this->db_connect(TRUE);
  397. }
  398. // --------------------------------------------------------------------
  399. /**
  400. * Reconnect
  401. *
  402. * Keep / reestablish the db connection if no queries have been
  403. * sent for a length of time exceeding the server's idle timeout.
  404. *
  405. * This is just a dummy method to allow drivers without such
  406. * functionality to not declare it, while others will override it.
  407. *
  408. * @return void
  409. */
  410. public function reconnect()
  411. {
  412. }
  413. // --------------------------------------------------------------------
  414. /**
  415. * Select database
  416. *
  417. * This is just a dummy method to allow drivers without such
  418. * functionality to not declare it, while others will override it.
  419. *
  420. * @return bool
  421. */
  422. public function db_select()
  423. {
  424. return TRUE;
  425. }
  426. // --------------------------------------------------------------------
  427. /**
  428. * Set client character set
  429. *
  430. * @param string
  431. * @return bool
  432. */
  433. public function db_set_charset($charset)
  434. {
  435. if (method_exists($this, '_db_set_charset') && ! $this->_db_set_charset($charset))
  436. {
  437. log_message('error', 'Unable to set database connection charset: '.$charset);
  438. if ($this->db_debug)
  439. {
  440. $this->display_error('db_unable_to_set_charset', $charset);
  441. }
  442. return FALSE;
  443. }
  444. return TRUE;
  445. }
  446. // --------------------------------------------------------------------
  447. /**
  448. * The name of the platform in use (mysql, mssql, etc...)
  449. *
  450. * @return string
  451. */
  452. public function platform()
  453. {
  454. return $this->dbdriver;
  455. }
  456. // --------------------------------------------------------------------
  457. /**
  458. * Database version number
  459. *
  460. * Returns a string containing the version of the database being used.
  461. * Most drivers will override this method.
  462. *
  463. * @return string
  464. */
  465. public function version()
  466. {
  467. if (isset($this->data_cache['version']))
  468. {
  469. return $this->data_cache['version'];
  470. }
  471. if (FALSE === ($sql = $this->_version()))
  472. {
  473. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  474. }
  475. $query = $this->query($sql)->row();
  476. return $this->data_cache['version'] = $query->ver;
  477. }
  478. // --------------------------------------------------------------------
  479. /**
  480. * Version number query string
  481. *
  482. * @return string
  483. */
  484. protected function _version()
  485. {
  486. return 'SELECT VERSION() AS ver';
  487. }
  488. // --------------------------------------------------------------------
  489. /**
  490. * Execute the query
  491. *
  492. * Accepts an SQL string as input and returns a result object upon
  493. * successful execution of a "read" type query. Returns boolean TRUE
  494. * upon successful execution of a "write" type query. Returns boolean
  495. * FALSE upon failure, and if the $db_debug variable is set to TRUE
  496. * will raise an error.
  497. *
  498. * @param string $sql
  499. * @param array $binds = FALSE An array of binding data
  500. * @param bool $return_object = NULL
  501. * @return mixed
  502. */
  503. public function query($sql, $binds = FALSE, $return_object = NULL)
  504. {
  505. if ($sql === '')
  506. {
  507. log_message('error', 'Invalid query: '.$sql);
  508. return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE;
  509. }
  510. elseif ( ! is_bool($return_object))
  511. {
  512. $return_object = ! $this->is_write_type($sql);
  513. }
  514. // Verify table prefix and replace if necessary
  515. if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
  516. {
  517. $sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
  518. }
  519. // Compile binds if needed
  520. if ($binds !== FALSE)
  521. {
  522. $sql = $this->compile_binds($sql, $binds);
  523. }
  524. // Is query caching enabled? If the query is a "read type"
  525. // we will load the caching class and return the previously
  526. // cached query if it exists
  527. if ($this->cache_on === TRUE && $return_object === TRUE && $this->_cache_init())
  528. {
  529. $this->load_rdriver();
  530. if (FALSE !== ($cache = $this->CACHE->read($sql)))
  531. {
  532. return $cache;
  533. }
  534. }
  535. // Save the query for debugging
  536. if ($this->save_queries === TRUE)
  537. {
  538. $this->queries[] = $sql;
  539. }
  540. // Start the Query Timer
  541. $time_start = microtime(TRUE);
  542. // Run the Query
  543. if (FALSE === ($this->result_id = $this->simple_query($sql)))
  544. {
  545. if ($this->save_queries === TRUE)
  546. {
  547. $this->query_times[] = 0;
  548. }
  549. // This will trigger a rollback if transactions are being used
  550. $this->_trans_status = FALSE;
  551. // Grab the error now, as we might run some additional queries before displaying the error
  552. $error = $this->error();
  553. // Log errors
  554. log_message('error', 'Query error: '.$error['message'].' - Invalid query: '.$sql);
  555. if ($this->db_debug)
  556. {
  557. // We call this function in order to roll-back queries
  558. // if transactions are enabled. If we don't call this here
  559. // the error message will trigger an exit, causing the
  560. // transactions to remain in limbo.
  561. if ($this->_trans_depth !== 0)
  562. {
  563. do
  564. {
  565. $this->trans_complete();
  566. }
  567. while ($this->_trans_depth !== 0);
  568. }
  569. // Display errors
  570. return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
  571. }
  572. return FALSE;
  573. }
  574. // Stop and aggregate the query time results
  575. $time_end = microtime(TRUE);
  576. $this->benchmark += $time_end - $time_start;
  577. if ($this->save_queries === TRUE)
  578. {
  579. $this->query_times[] = $time_end - $time_start;
  580. }
  581. // Increment the query counter
  582. $this->query_count++;
  583. // Will we have a result object instantiated? If not - we'll simply return TRUE
  584. if ($return_object !== TRUE)
  585. {
  586. // If caching is enabled we'll auto-cleanup any existing files related to this particular URI
  587. if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
  588. {
  589. $this->CACHE->delete();
  590. }
  591. return TRUE;
  592. }
  593. // Load and instantiate the result driver
  594. $driver = $this->load_rdriver();
  595. $RES = new $driver($this);
  596. // Is query caching enabled? If so, we'll serialize the
  597. // result object and save it to a cache file.
  598. if ($this->cache_on === TRUE && $this->_cache_init())
  599. {
  600. // We'll create a new instance of the result object
  601. // only without the platform specific driver since
  602. // we can't use it with cached data (the query result
  603. // resource ID won't be any good once we've cached the
  604. // result object, so we'll have to compile the data
  605. // and save it)
  606. $CR = new CI_DB_result($this);
  607. $CR->result_object = $RES->result_object();
  608. $CR->result_array = $RES->result_array();
  609. $CR->num_rows = $RES->num_rows();
  610. // Reset these since cached objects can not utilize resource IDs.
  611. $CR->conn_id = NULL;
  612. $CR->result_id = NULL;
  613. $this->CACHE->write($sql, $CR);
  614. }
  615. return $RES;
  616. }
  617. // --------------------------------------------------------------------
  618. /**
  619. * Load the result drivers
  620. *
  621. * @return string the name of the result class
  622. */
  623. public function load_rdriver()
  624. {
  625. $driver = 'CI_DB_'.$this->dbdriver.'_result';
  626. if ( ! class_exists($driver, FALSE))
  627. {
  628. require_once(BASEPATH.'database/DB_result.php');
  629. require_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
  630. }
  631. return $driver;
  632. }
  633. // --------------------------------------------------------------------
  634. /**
  635. * Simple Query
  636. * This is a simplified version of the query() function. Internally
  637. * we only use it when running transaction commands since they do
  638. * not require all the features of the main query() function.
  639. *
  640. * @param string the sql query
  641. * @return mixed
  642. */
  643. public function simple_query($sql)
  644. {
  645. if ( ! $this->conn_id)
  646. {
  647. $this->initialize();
  648. }
  649. return $this->_execute($sql);
  650. }
  651. // --------------------------------------------------------------------
  652. /**
  653. * Disable Transactions
  654. * This permits transactions to be disabled at run-time.
  655. *
  656. * @return void
  657. */
  658. public function trans_off()
  659. {
  660. $this->trans_enabled = FALSE;
  661. }
  662. // --------------------------------------------------------------------
  663. /**
  664. * Enable/disable Transaction Strict Mode
  665. * When strict mode is enabled, if you are running multiple groups of
  666. * transactions, if one group fails all groups will be rolled back.
  667. * If strict mode is disabled, each group is treated autonomously, meaning
  668. * a failure of one group will not affect any others
  669. *
  670. * @param bool $mode = TRUE
  671. * @return void
  672. */
  673. public function trans_strict($mode = TRUE)
  674. {
  675. $this->trans_strict = is_bool($mode) ? $mode : TRUE;
  676. }
  677. // --------------------------------------------------------------------
  678. /**
  679. * Start Transaction
  680. *
  681. * @param bool $test_mode = FALSE
  682. * @return void
  683. */
  684. public function trans_start($test_mode = FALSE)
  685. {
  686. if ( ! $this->trans_enabled)
  687. {
  688. return FALSE;
  689. }
  690. // When transactions are nested we only begin/commit/rollback the outermost ones
  691. if ($this->_trans_depth > 0)
  692. {
  693. $this->_trans_depth += 1;
  694. return;
  695. }
  696. $this->trans_begin($test_mode);
  697. $this->_trans_depth += 1;
  698. }
  699. // --------------------------------------------------------------------
  700. /**
  701. * Complete Transaction
  702. *
  703. * @return bool
  704. */
  705. public function trans_complete()
  706. {
  707. if ( ! $this->trans_enabled)
  708. {
  709. return FALSE;
  710. }
  711. // When transactions are nested we only begin/commit/rollback the outermost ones
  712. if ($this->_trans_depth > 1)
  713. {
  714. $this->_trans_depth -= 1;
  715. return TRUE;
  716. }
  717. else
  718. {
  719. $this->_trans_depth = 0;
  720. }
  721. // The query() function will set this flag to FALSE in the event that a query failed
  722. if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE)
  723. {
  724. $this->trans_rollback();
  725. // If we are NOT running in strict mode, we will reset
  726. // the _trans_status flag so that subsequent groups of transactions
  727. // will be permitted.
  728. if ($this->trans_strict === FALSE)
  729. {
  730. $this->_trans_status = TRUE;
  731. }
  732. log_message('debug', 'DB Transaction Failure');
  733. return FALSE;
  734. }
  735. $this->trans_commit();
  736. return TRUE;
  737. }
  738. // --------------------------------------------------------------------
  739. /**
  740. * Lets you retrieve the transaction flag to determine if it has failed
  741. *
  742. * @return bool
  743. */
  744. public function trans_status()
  745. {
  746. return $this->_trans_status;
  747. }
  748. // --------------------------------------------------------------------
  749. /**
  750. * Compile Bindings
  751. *
  752. * @param string the sql statement
  753. * @param array an array of bind data
  754. * @return string
  755. */
  756. public function compile_binds($sql, $binds)
  757. {
  758. if (empty($binds) OR empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
  759. {
  760. return $sql;
  761. }
  762. elseif ( ! is_array($binds))
  763. {
  764. $binds = array($binds);
  765. $bind_count = 1;
  766. }
  767. else
  768. {
  769. // Make sure we're using numeric keys
  770. $binds = array_values($binds);
  771. $bind_count = count($binds);
  772. }
  773. // We'll need the marker length later
  774. $ml = strlen($this->bind_marker);
  775. // Make sure not to replace a chunk inside a string that happens to match the bind marker
  776. if ($c = preg_match_all("/'[^']*'/i", $sql, $matches))
  777. {
  778. $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i',
  779. str_replace($matches[0],
  780. str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]),
  781. $sql, $c),
  782. $matches, PREG_OFFSET_CAPTURE);
  783. // Bind values' count must match the count of markers in the query
  784. if ($bind_count !== $c)
  785. {
  786. return $sql;
  787. }
  788. }
  789. elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count)
  790. {
  791. return $sql;
  792. }
  793. do
  794. {
  795. $c--;
  796. $sql = substr_replace($sql, $this->escape($binds[$c]), $matches[0][$c][1], $ml);
  797. }
  798. while ($c !== 0);
  799. return $sql;
  800. }
  801. // --------------------------------------------------------------------
  802. /**
  803. * Determines if a query is a "write" type.
  804. *
  805. * @param string An SQL query string
  806. * @return bool
  807. */
  808. public function is_write_type($sql)
  809. {
  810. return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s/i', $sql);
  811. }
  812. // --------------------------------------------------------------------
  813. /**
  814. * Calculate the aggregate query elapsed time
  815. *
  816. * @param int The number of decimal places
  817. * @return int
  818. */
  819. public function elapsed_time($decimals = 6)
  820. {
  821. return number_format($this->benchmark, $decimals);
  822. }
  823. // --------------------------------------------------------------------
  824. /**
  825. * Returns the total number of queries
  826. *
  827. * @return int
  828. */
  829. public function total_queries()
  830. {
  831. return $this->query_count;
  832. }
  833. // --------------------------------------------------------------------
  834. /**
  835. * Returns the last query that was executed
  836. *
  837. * @return string
  838. */
  839. public function last_query()
  840. {
  841. return end($this->queries);
  842. }
  843. // --------------------------------------------------------------------
  844. /**
  845. * "Smart" Escape String
  846. *
  847. * Escapes data based on type
  848. * Sets boolean and null types
  849. *
  850. * @param string
  851. * @return mixed
  852. */
  853. public function escape($str)
  854. {
  855. if (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))
  856. {
  857. return "'".$this->escape_str($str)."'";
  858. }
  859. elseif (is_bool($str))
  860. {
  861. return ($str === FALSE) ? 0 : 1;
  862. }
  863. elseif ($str === NULL)
  864. {
  865. return 'NULL';
  866. }
  867. return $str;
  868. }
  869. // --------------------------------------------------------------------
  870. /**
  871. * Escape String
  872. *
  873. * @param string $str
  874. * @param bool $like Whether or not the string will be used in a LIKE condition
  875. * @return string
  876. */
  877. public function escape_str($str, $like = FALSE)
  878. {
  879. if (is_array($str))
  880. {
  881. foreach ($str as $key => $val)
  882. {
  883. $str[$key] = $this->escape_str($val, $like);
  884. }
  885. return $str;
  886. }
  887. $str = $this->_escape_str($str);
  888. // escape LIKE condition wildcards
  889. if ($like === TRUE)
  890. {
  891. return str_replace(
  892. array($this->_like_escape_chr, '%', '_'),
  893. array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
  894. $str
  895. );
  896. }
  897. return $str;
  898. }
  899. // --------------------------------------------------------------------
  900. /**
  901. * Escape LIKE String
  902. *
  903. * Calls the individual driver for platform
  904. * specific escaping for LIKE conditions
  905. *
  906. * @param string|string[]
  907. * @return mixed
  908. */
  909. public function escape_like_str($str)
  910. {
  911. return $this->escape_str($str, TRUE);
  912. }
  913. // --------------------------------------------------------------------
  914. /**
  915. * Platform-dependant string escape
  916. *
  917. * @param string
  918. * @return string
  919. */
  920. protected function _escape_str($str)
  921. {
  922. return str_replace("'", "''", remove_invisible_characters($str));
  923. }
  924. // --------------------------------------------------------------------
  925. /**
  926. * Primary
  927. *
  928. * Retrieves the primary key. It assumes that the row in the first
  929. * position is the primary key
  930. *
  931. * @param string the table name
  932. * @return string
  933. */
  934. public function primary($table = '')
  935. {
  936. $fields = $this->list_fields($table);
  937. return is_array($fields) ? current($fields) : FALSE;
  938. }
  939. // --------------------------------------------------------------------
  940. /**
  941. * "Count All" query
  942. *
  943. * Generates a platform-specific query string that counts all records in
  944. * the specified database
  945. *
  946. * @param string
  947. * @return int
  948. */
  949. public function count_all($table = '')
  950. {
  951. if ($table === '')
  952. {
  953. return 0;
  954. }
  955. $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
  956. if ($query->num_rows() === 0)
  957. {
  958. return 0;
  959. }
  960. $query = $query->row();
  961. $this->_reset_select();
  962. return (int) $query->numrows;
  963. }
  964. // --------------------------------------------------------------------
  965. /**
  966. * Returns an array of table names
  967. *
  968. * @param string $constrain_by_prefix = FALSE
  969. * @return array
  970. */
  971. public function list_tables($constrain_by_prefix = FALSE)
  972. {
  973. // Is there a cached result?
  974. if (isset($this->data_cache['table_names']))
  975. {
  976. return $this->data_cache['table_names'];
  977. }
  978. if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
  979. {
  980. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  981. }
  982. $this->data_cache['table_names'] = array();
  983. $query = $this->query($sql);
  984. foreach ($query->result_array() as $row)
  985. {
  986. // Do we know from which column to get the table name?
  987. if ( ! isset($key))
  988. {
  989. if (isset($row['table_name']))
  990. {
  991. $key = 'table_name';
  992. }
  993. elseif (isset($row['TABLE_NAME']))
  994. {
  995. $key = 'TABLE_NAME';
  996. }
  997. else
  998. {
  999. /* We have no other choice but to just get the first element's key.
  1000. * Due to array_shift() accepting its argument by reference, if
  1001. * E_STRICT is on, this would trigger a warning. So we'll have to
  1002. * assign it first.
  1003. */
  1004. $key = array_keys($row);
  1005. $key = array_shift($key);
  1006. }
  1007. }
  1008. $this->data_cache['table_names'][] = $row[$key];
  1009. }
  1010. return $this->data_cache['table_names'];
  1011. }
  1012. // --------------------------------------------------------------------
  1013. /**
  1014. * Determine if a particular table exists
  1015. *
  1016. * @param string $table_name
  1017. * @return bool
  1018. */
  1019. public function table_exists($table_name)
  1020. {
  1021. return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables());
  1022. }
  1023. // --------------------------------------------------------------------
  1024. /**
  1025. * Fetch Field Names
  1026. *
  1027. * @param string the table name
  1028. * @return array
  1029. */
  1030. public function list_fields($table = '')
  1031. {
  1032. // Is there a cached result?
  1033. if (isset($this->data_cache['field_names'][$table]))
  1034. {
  1035. return $this->data_cache['field_names'][$table];
  1036. }
  1037. if ($table === '')
  1038. {
  1039. return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
  1040. }
  1041. if (FALSE === ($sql = $this->_list_columns($table)))
  1042. {
  1043. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1044. }
  1045. $query = $this->query($sql);
  1046. $this->data_cache['field_names'][$table] = array();
  1047. foreach ($query->result_array() as $row)
  1048. {
  1049. // Do we know from where to get the column's name?
  1050. if ( ! isset($key))
  1051. {
  1052. if (isset($row['column_name']))
  1053. {
  1054. $key = 'column_name';
  1055. }
  1056. elseif (isset($row['COLUMN_NAME']))
  1057. {
  1058. $key = 'COLUMN_NAME';
  1059. }
  1060. else
  1061. {
  1062. // We have no other choice but to just get the first element's key.
  1063. $key = key($row);
  1064. }
  1065. }
  1066. $this->data_cache['field_names'][$table][] = $row[$key];
  1067. }
  1068. return $this->data_cache['field_names'][$table];
  1069. }
  1070. // --------------------------------------------------------------------
  1071. /**
  1072. * Determine if a particular field exists
  1073. *
  1074. * @param string
  1075. * @param string
  1076. * @return bool
  1077. */
  1078. public function field_exists($field_name, $table_name)
  1079. {
  1080. return in_array($field_name, $this->list_fields($table_name));
  1081. }
  1082. // --------------------------------------------------------------------
  1083. /**
  1084. * Returns an object with field data
  1085. *
  1086. * @param string the table name
  1087. * @return object
  1088. */
  1089. public function field_data($table = '')
  1090. {
  1091. if ($table === '')
  1092. {
  1093. return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
  1094. }
  1095. $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
  1096. return $query->field_data();
  1097. }
  1098. // --------------------------------------------------------------------
  1099. /**
  1100. * Escape the SQL Identifiers
  1101. *
  1102. * This function escapes column and table names
  1103. *
  1104. * @param mixed
  1105. * @return mixed
  1106. */
  1107. public function escape_identifiers($item)
  1108. {
  1109. if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers))
  1110. {
  1111. return $item;
  1112. }
  1113. elseif (is_array($item))
  1114. {
  1115. foreach ($item as $key => $value)
  1116. {
  1117. $item[$key] = $this->escape_identifiers($value);
  1118. }
  1119. return $item;
  1120. }
  1121. // Avoid breaking functions and literal values inside queries
  1122. elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE)
  1123. {
  1124. return $item;
  1125. }
  1126. static $preg_ec = array();
  1127. if (empty($preg_ec))
  1128. {
  1129. if (is_array($this->_escape_char))
  1130. {
  1131. $preg_ec = array(
  1132. preg_quote($this->_escape_char[0], '/'),
  1133. preg_quote($this->_escape_char[1], '/'),
  1134. $this->_escape_char[0],
  1135. $this->_escape_char[1]
  1136. );
  1137. }
  1138. else
  1139. {
  1140. $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/');
  1141. $preg_ec[2] = $preg_ec[3] = $this->_escape_char;
  1142. }
  1143. }
  1144. foreach ($this->_reserved_identifiers as $id)
  1145. {
  1146. if (strpos($item, '.'.$id) !== FALSE)
  1147. {
  1148. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item);
  1149. }
  1150. }
  1151. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item);
  1152. }
  1153. // --------------------------------------------------------------------
  1154. /**
  1155. * Generate an insert string
  1156. *
  1157. * @param string the table upon which the query will be performed
  1158. * @param array an associative array data of key/values
  1159. * @return string
  1160. */
  1161. public function insert_string($table, $data)
  1162. {
  1163. $fields = $values = array();
  1164. foreach ($data as $key => $val)
  1165. {
  1166. $fields[] = $this->escape_identifiers($key);
  1167. $values[] = $this->escape($val);
  1168. }
  1169. return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  1170. }
  1171. // --------------------------------------------------------------------
  1172. /**
  1173. * Insert statement
  1174. *
  1175. * Generates a platform-specific insert string from the supplied data
  1176. *
  1177. * @param string the table name
  1178. * @param array the insert keys
  1179. * @param array the insert values
  1180. * @return string
  1181. */
  1182. protected function _insert($table, $keys, $values)
  1183. {
  1184. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1185. }
  1186. // --------------------------------------------------------------------
  1187. /**
  1188. * Generate an update string
  1189. *
  1190. * @param string the table upon which the query will be performed
  1191. * @param array an associative array data of key/values
  1192. * @param mixed the "where" statement
  1193. * @return string
  1194. */
  1195. public function update_string($table, $data, $where)
  1196. {
  1197. if (empty($where))
  1198. {
  1199. return FALSE;
  1200. }
  1201. $this->where($where);
  1202. $fields = array();
  1203. foreach ($data as $key => $val)
  1204. {
  1205. $fields[$this->protect_identifiers($key)] = $this->escape($val);
  1206. }
  1207. $sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields);
  1208. $this->_reset_write();
  1209. return $sql;
  1210. }
  1211. // --------------------------------------------------------------------
  1212. /**
  1213. * Update statement
  1214. *
  1215. * Generates a platform-specific update string from the supplied data
  1216. *
  1217. * @param string the table name
  1218. * @param array the update data
  1219. * @return string
  1220. */
  1221. protected function _update($table, $values)
  1222. {
  1223. foreach ($values as $key => $val)
  1224. {
  1225. $valstr[] = $key.' = '.$val;
  1226. }
  1227. return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
  1228. .$this->_compile_wh('qb_where')
  1229. .$this->_compile_order_by()
  1230. .($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
  1231. }
  1232. // --------------------------------------------------------------------
  1233. /**
  1234. * Tests whether the string has an SQL operator
  1235. *
  1236. * @param string
  1237. * @return bool
  1238. */
  1239. protected function _has_operator($str)
  1240. {
  1241. return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
  1242. }
  1243. // --------------------------------------------------------------------
  1244. /**
  1245. * Returns the SQL string operator
  1246. *
  1247. * @param string
  1248. * @return string
  1249. */
  1250. protected function _get_operator($str)
  1251. {
  1252. static $_operators;
  1253. if (empty($_operators))
  1254. {
  1255. $_les = ($this->_like_escape_str !== '')
  1256. ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/')
  1257. : '';
  1258. $_operators = array(
  1259. '\s*(?:<|>|!)?=\s*', // =, <=, >=, !=
  1260. '\s*<>?\s*', // <, <>
  1261. '\s*>\s*', // >
  1262. '\s+IS NULL', // IS NULL
  1263. '\s+IS NOT NULL', // IS NOT NULL
  1264. '\s+EXISTS\s*\([^\)]+\)', // EXISTS(sql)
  1265. '\s+NOT EXISTS\s*\([^\)]+\)', // NOT EXISTS(sql)
  1266. '\s+BETWEEN\s+\S+\s+AND\s+\S+', // BETWEEN value AND value
  1267. '\s+IN\s*\([^\)]+\)', // IN(list)
  1268. '\s+NOT IN\s*\([^\)]+\)', // NOT IN (list)
  1269. '\s+LIKE\s+\S+'.$_les, // LIKE 'expr'[ ESCAPE '%s']
  1270. '\s+NOT LIKE\s+\S+'.$_les // NOT LIKE 'expr'[ ESCAPE '%s']
  1271. );
  1272. }
  1273. return preg_match('/'.implode('|', $_operators).'/i', $str, $match)
  1274. ? $match[0] : FALSE;
  1275. }
  1276. // --------------------------------------------------------------------
  1277. /**
  1278. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  1279. *
  1280. * @param string $function Function name
  1281. * @return mixed
  1282. */
  1283. public function call_function($function)
  1284. {
  1285. $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
  1286. if (FALSE === strpos($driver, $function))
  1287. {
  1288. $function = $driver.$function;
  1289. }
  1290. if ( ! function_exists($function))
  1291. {
  1292. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1293. }
  1294. return (func_num_args() > 1)
  1295. ? call_user_func_array($function, array_slice(func_get_args(), 1))
  1296. : call_user_func($function);
  1297. }
  1298. // --------------------------------------------------------------------
  1299. /**
  1300. * Set Cache Directory Path
  1301. *
  1302. * @param string the path to the cache directory
  1303. * @return void
  1304. */
  1305. public function cache_set_path($path = '')
  1306. {
  1307. $this->cachedir = $path;
  1308. }
  1309. // --------------------------------------------------------------------
  1310. /**
  1311. * Enable Query Caching
  1312. *
  1313. * @return bool cache_on value
  1314. */
  1315. public function cache_on()
  1316. {
  1317. return $this->cache_on = TRUE;
  1318. }
  1319. // --------------------------------------------------------------------
  1320. /**
  1321. * Disable Query Caching
  1322. *
  1323. * @return bool cache_on value
  1324. */
  1325. public function cache_off()
  1326. {
  1327. return $this->cache_on = FALSE;
  1328. }
  1329. // --------------------------------------------------------------------
  1330. /**
  1331. * Delete the cache files associated with a particular URI
  1332. *
  1333. * @param string $segment_one = ''
  1334. * @param string $segment_two = ''
  1335. * @return bool
  1336. */
  1337. public function cache_delete($segment_one = '', $segment_two = '')
  1338. {
  1339. return $this->_cache_init()
  1340. ? $this->CACHE->delete($segment_one, $segment_two)
  1341. : FALSE;
  1342. }
  1343. // --------------------------------------------------------------------
  1344. /**
  1345. * Delete All cache files
  1346. *
  1347. * @return bool
  1348. */
  1349. public function cache_delete_all()
  1350. {
  1351. return $this->_cache_init()
  1352. ? $this->CACHE->delete_all()
  1353. : FALSE;
  1354. }
  1355. // --------------------------------------------------------------------
  1356. /**
  1357. * Initialize the Cache Class
  1358. *
  1359. * @return bool
  1360. */
  1361. protected function _cache_init()
  1362. {
  1363. if ( ! class_exists('CI_DB_Cache', FALSE))
  1364. {
  1365. require_once(BASEPATH.'database/DB_cache.php');
  1366. }
  1367. elseif (is_object($this->CACHE))
  1368. {
  1369. return TRUE;
  1370. }
  1371. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  1372. return TRUE;
  1373. }
  1374. // --------------------------------------------------------------------
  1375. /**
  1376. * Close DB Connection
  1377. *
  1378. * @return void
  1379. */
  1380. public function close()
  1381. {
  1382. if ($this->conn_id)
  1383. {
  1384. $this->_close();
  1385. $this->conn_id = FALSE;
  1386. }
  1387. }
  1388. // --------------------------------------------------------------------
  1389. /**
  1390. * Close DB Connection
  1391. *
  1392. * This method would be overriden by most of the drivers.
  1393. *
  1394. * @return void
  1395. */
  1396. protected function _close()
  1397. {
  1398. $this->conn_id = FALSE;
  1399. }
  1400. // --------------------------------------------------------------------
  1401. /**
  1402. * Display an error message
  1403. *
  1404. * @param string the error message
  1405. * @param string any "swap" values
  1406. * @param bool whether to localize the message
  1407. * @return string sends the application/views/errors/error_db.php template
  1408. */
  1409. public function display_error($error = '', $swap = '', $native = FALSE)
  1410. {
  1411. $LANG =& load_class('Lang', 'core');
  1412. $LANG->load('db');
  1413. $heading = $LANG->line('db_error_heading');
  1414. if ($native === TRUE)
  1415. {
  1416. $message = (array) $error;
  1417. }
  1418. else
  1419. {
  1420. $message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($error)));
  1421. }
  1422. // Find the most likely culprit of the error by going through
  1423. // the backtrace until the source file is no longer in the
  1424. // database folder.
  1425. $trace = debug_backtrace();
  1426. foreach ($trace as $call)
  1427. {
  1428. if (isset($call['file'], $call['class']))
  1429. {
  1430. // We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes
  1431. if (DIRECTORY_SEPARATOR !== '/')
  1432. {
  1433. $call['file'] = str_replace('\\', '/', $call['file']);
  1434. }
  1435. if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE)
  1436. {
  1437. // Found it - use a relative path for safety
  1438. $message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']);
  1439. $message[] = 'Line Number: '.$call['line'];
  1440. break;
  1441. }
  1442. }
  1443. }
  1444. $error =& load_class('Exceptions', 'core');
  1445. echo $error->show_error($heading, $message, 'error_db');
  1446. exit(8); // EXIT_DATABASE
  1447. }
  1448. // --------------------------------------------------------------------
  1449. /**
  1450. * Protect Identifiers
  1451. *
  1452. * This function is used extensively by the Query Builder class, and by
  1453. * a couple functions in this class.
  1454. * It takes a column or table name (optionally with an alias) and inserts
  1455. * the table prefix onto it. Some logic is necessary in order to deal with
  1456. * column names that include the path. Consider a query like this:
  1457. *
  1458. * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
  1459. *
  1460. * Or a query with aliasing:
  1461. *
  1462. * SELECT m.member_id, m.member_name FROM members AS m
  1463. *
  1464. * Since the column name can include up to four segments (host, DB, table, column)
  1465. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1466. * insert the table prefix (if it exists) in the proper position, and escape only
  1467. * the correct identifiers.
  1468. *
  1469. * @param string
  1470. * @param bool
  1471. * @param mixed
  1472. * @param bool
  1473. * @return string
  1474. */
  1475. public function protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1476. {
  1477. if ( ! is_bool($protect_identifiers))
  1478. {
  1479. $protect_identifiers = $this->_protect_identifiers;
  1480. }
  1481. if (is_array($item))
  1482. {
  1483. $escaped_array = array();
  1484. foreach ($item as $k => $v)
  1485. {
  1486. $escaped_array[$this->protect_identifiers($k)] = $this->protect_identifiers($v, $prefix_single, $protect_identifiers, $field_exists);
  1487. }
  1488. return $escaped_array;
  1489. }
  1490. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1491. // If a parenthesis is found we know that we do not need to
  1492. // escape the data or add a prefix. There's probably a more graceful
  1493. // way to deal with this, but I'm not thinking of it -- Rick
  1494. //
  1495. // Added exception for single quotes as well, we don't want to alter
  1496. // literal strings. -- Narf
  1497. if (strpos($item, '(') !== FALSE OR strpos($item, "'") !== FALSE)
  1498. {
  1499. return $item;
  1500. }
  1501. // Convert tabs or multiple spaces into single spaces
  1502. $item = preg_replace('/\s+/', ' ', $item);
  1503. // If the item has an alias declaration we remove it and set it aside.
  1504. // Note: strripos() is used in order to support spaces in table names
  1505. if ($offset = strripos($item, ' AS '))
  1506. {
  1507. $alias = ($protect_identifiers)
  1508. ? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4))
  1509. : substr($item, $offset);
  1510. $item = substr($item, 0, $offset);
  1511. }
  1512. elseif ($offset = strrpos($item, ' '))
  1513. {
  1514. $alias = ($protect_identifiers)
  1515. ? ' '.$this->escape_identifiers(substr($item, $offset + 1))
  1516. : substr($item, $offset);
  1517. $item = substr($item, 0, $offset);
  1518. }
  1519. else
  1520. {
  1521. $alias = '';
  1522. }
  1523. // Break the string apart if it contains periods, then insert the table prefix
  1524. // in the correct location, assuming the period doesn't indicate that we're dealing
  1525. // with an alias. While we're at it, we will escape the components
  1526. if (strpos($item, '.') !== FALSE)
  1527. {
  1528. $parts = explode('.', $item);
  1529. // Does the first segment of the exploded item match
  1530. // one of the aliases previously identified? If so,
  1531. // we have nothing more to do other than escape the item
  1532. if (in_array($parts[0], $this->qb_aliased_tables))
  1533. {
  1534. if ($protect_identifiers === TRUE)
  1535. {
  1536. foreach ($parts as $key => $val)
  1537. {
  1538. if ( ! in_array($val, $this->_reserved_identifiers))
  1539. {
  1540. $parts[$key] = $this->escape_identifiers($val);
  1541. }
  1542. }
  1543. $item = implode('.', $parts);
  1544. }
  1545. return $item.$alias;
  1546. }
  1547. // Is there a table prefix defined in the config file? If not, no need to do anything
  1548. if ($this->dbprefix !== '')
  1549. {
  1550. // We now add the table prefix based on some logic.
  1551. // Do we have 4 segments (hostname.database.table.column)?
  1552. // If so, we add the table prefix to the column name in the 3rd segment.
  1553. if (isset($parts[3]))
  1554. {
  1555. $i = 2;
  1556. }
  1557. // Do we have 3 segments (database.table.column)?
  1558. // If so, we add the table prefix to the column name in 2nd position
  1559. elseif (isset($parts[2]))
  1560. {
  1561. $i = 1;
  1562. }
  1563. // Do we have 2 segments (table.column)?
  1564. // If so, we add the table prefix to the column name in 1st segment
  1565. else
  1566. {
  1567. $i = 0;
  1568. }
  1569. // This flag is set when the supplied $item does not contain a field name.
  1570. // This can happen when this function is being called from a JOIN.
  1571. if ($field_exists === FALSE)
  1572. {
  1573. $i++;
  1574. }
  1575. // Verify table prefix and replace if necessary
  1576. if ($this->swap_pre !== '' && strpos($parts[$i], $this->swap_pre) === 0)
  1577. {
  1578. $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]);
  1579. }
  1580. // We only add the table prefix if it does not already exist
  1581. elseif (strpos($parts[$i], $this->dbprefix) !== 0)
  1582. {
  1583. $parts[$i] = $this->dbprefix.$parts[$i];
  1584. }
  1585. // Put the parts back together
  1586. $item = implode('.', $parts);
  1587. }
  1588. if ($protect_identifiers === TRUE)
  1589. {
  1590. $item = $this->escape_identifiers($item);
  1591. }
  1592. return $item.$alias;
  1593. }
  1594. // Is there a table prefix? If not, no need to insert it
  1595. if ($this->dbprefix !== '')
  1596. {
  1597. // Verify table prefix and replace if necessary
  1598. if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
  1599. {
  1600. $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
  1601. }
  1602. // Do we prefix an item with no segments?
  1603. elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
  1604. {
  1605. $item = $this->dbprefix.$item;
  1606. }
  1607. }
  1608. if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
  1609. {
  1610. $item = $this->escape_identifiers($item);
  1611. }
  1612. return $item.$alias;
  1613. }
  1614. // --------------------------------------------------------------------
  1615. /**
  1616. * Dummy method that allows Query Builder class to be disabled
  1617. * and keep count_all() working.
  1618. *
  1619. * @return void
  1620. */
  1621. protected function _reset_select()
  1622. {
  1623. }
  1624. }
  1625. /* End of file DB_driver.php */
  1626. /* Location: ./system/database/DB_driver.php */