PageRenderTime 107ms CodeModel.GetById 23ms RepoModel.GetById 4ms app.codeStats 1ms

/system/database/DB_driver.php

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