PageRenderTime 69ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/system/database/DB_driver.php

https://github.com/coderkid/No-CMS
PHP | 1868 lines | 1121 code | 173 blank | 574 comment | 74 complexity | 9b4108afae23cbcad32ceeebe7adc06c MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-2.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 - 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. if ($this->_trans_depth !== 0)
  545. {
  546. do
  547. {
  548. $this->trans_complete();
  549. }
  550. while ($this->_trans_depth !== 0);
  551. }
  552. // Display errors
  553. return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
  554. }
  555. return FALSE;
  556. }
  557. // Stop and aggregate the query time results
  558. $time_end = microtime(TRUE);
  559. $this->benchmark += $time_end - $time_start;
  560. if ($this->save_queries === TRUE)
  561. {
  562. $this->query_times[] = $time_end - $time_start;
  563. }
  564. // Increment the query counter
  565. $this->query_count++;
  566. // Will we have a result object instantiated? If not - we'll simply return TRUE
  567. if ($return_object !== TRUE)
  568. {
  569. // If caching is enabled we'll auto-cleanup any existing files related to this particular URI
  570. if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
  571. {
  572. $this->CACHE->delete();
  573. }
  574. return TRUE;
  575. }
  576. // Return TRUE if we don't need to create a result object
  577. if ($return_object !== TRUE)
  578. {
  579. return TRUE;
  580. }
  581. // Load and instantiate the result driver
  582. $driver = $this->load_rdriver();
  583. $RES = new $driver($this);
  584. // Is query caching enabled? If so, we'll serialize the
  585. // result object and save it to a cache file.
  586. if ($this->cache_on === TRUE && $this->_cache_init())
  587. {
  588. // We'll create a new instance of the result object
  589. // only without the platform specific driver since
  590. // we can't use it with cached data (the query result
  591. // resource ID won't be any good once we've cached the
  592. // result object, so we'll have to compile the data
  593. // and save it)
  594. $CR = new CI_DB_result($this);
  595. $CR->result_object = $RES->result_object();
  596. $CR->result_array = $RES->result_array();
  597. $CR->num_rows = $RES->num_rows();
  598. // Reset these since cached objects can not utilize resource IDs.
  599. $CR->conn_id = NULL;
  600. $CR->result_id = NULL;
  601. $this->CACHE->write($sql, $CR);
  602. }
  603. return $RES;
  604. }
  605. // --------------------------------------------------------------------
  606. /**
  607. * Load the result drivers
  608. *
  609. * @return string the name of the result class
  610. */
  611. public function load_rdriver()
  612. {
  613. $driver = 'CI_DB_'.$this->dbdriver.'_result';
  614. if ( ! class_exists($driver, FALSE))
  615. {
  616. include_once(BASEPATH.'database/DB_result.php');
  617. include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
  618. }
  619. return $driver;
  620. }
  621. // --------------------------------------------------------------------
  622. /**
  623. * Simple Query
  624. * This is a simplified version of the query() function. Internally
  625. * we only use it when running transaction commands since they do
  626. * not require all the features of the main query() function.
  627. *
  628. * @param string the sql query
  629. * @return mixed
  630. */
  631. public function simple_query($sql)
  632. {
  633. if ( ! $this->conn_id)
  634. {
  635. $this->initialize();
  636. }
  637. return $this->_execute($sql);
  638. }
  639. // --------------------------------------------------------------------
  640. /**
  641. * Disable Transactions
  642. * This permits transactions to be disabled at run-time.
  643. *
  644. * @return void
  645. */
  646. public function trans_off()
  647. {
  648. $this->trans_enabled = FALSE;
  649. }
  650. // --------------------------------------------------------------------
  651. /**
  652. * Enable/disable Transaction Strict Mode
  653. * When strict mode is enabled, if you are running multiple groups of
  654. * transactions, if one group fails all groups will be rolled back.
  655. * If strict mode is disabled, each group is treated autonomously, meaning
  656. * a failure of one group will not affect any others
  657. *
  658. * @param bool $mode = TRUE
  659. * @return void
  660. */
  661. public function trans_strict($mode = TRUE)
  662. {
  663. $this->trans_strict = is_bool($mode) ? $mode : TRUE;
  664. }
  665. // --------------------------------------------------------------------
  666. /**
  667. * Start Transaction
  668. *
  669. * @param bool $test_mode = FALSE
  670. * @return void
  671. */
  672. public function trans_start($test_mode = FALSE)
  673. {
  674. if ( ! $this->trans_enabled)
  675. {
  676. return FALSE;
  677. }
  678. // When transactions are nested we only begin/commit/rollback the outermost ones
  679. if ($this->_trans_depth > 0)
  680. {
  681. $this->_trans_depth += 1;
  682. return;
  683. }
  684. $this->trans_begin($test_mode);
  685. $this->_trans_depth += 1;
  686. }
  687. // --------------------------------------------------------------------
  688. /**
  689. * Complete Transaction
  690. *
  691. * @return bool
  692. */
  693. public function trans_complete()
  694. {
  695. if ( ! $this->trans_enabled)
  696. {
  697. return FALSE;
  698. }
  699. // When transactions are nested we only begin/commit/rollback the outermost ones
  700. if ($this->_trans_depth > 1)
  701. {
  702. $this->_trans_depth -= 1;
  703. return TRUE;
  704. }
  705. else
  706. {
  707. $this->_trans_depth = 0;
  708. }
  709. // The query() function will set this flag to FALSE in the event that a query failed
  710. if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE)
  711. {
  712. $this->trans_rollback();
  713. // If we are NOT running in strict mode, we will reset
  714. // the _trans_status flag so that subsequent groups of transactions
  715. // will be permitted.
  716. if ($this->trans_strict === FALSE)
  717. {
  718. $this->_trans_status = TRUE;
  719. }
  720. log_message('debug', 'DB Transaction Failure');
  721. return FALSE;
  722. }
  723. $this->trans_commit();
  724. return TRUE;
  725. }
  726. // --------------------------------------------------------------------
  727. /**
  728. * Lets you retrieve the transaction flag to determine if it has failed
  729. *
  730. * @return bool
  731. */
  732. public function trans_status()
  733. {
  734. return $this->_trans_status;
  735. }
  736. // --------------------------------------------------------------------
  737. /**
  738. * Compile Bindings
  739. *
  740. * @param string the sql statement
  741. * @param array an array of bind data
  742. * @return string
  743. */
  744. public function compile_binds($sql, $binds)
  745. {
  746. if (empty($binds) OR empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
  747. {
  748. return $sql;
  749. }
  750. elseif ( ! is_array($binds))
  751. {
  752. $binds = array($binds);
  753. $bind_count = 1;
  754. }
  755. else
  756. {
  757. // Make sure we're using numeric keys
  758. $binds = array_values($binds);
  759. $bind_count = count($binds);
  760. }
  761. // We'll need the marker length later
  762. $ml = strlen($this->bind_marker);
  763. // Make sure not to replace a chunk inside a string that happens to match the bind marker
  764. if ($c = preg_match_all("/'[^']*'/i", $sql, $matches))
  765. {
  766. $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i',
  767. str_replace($matches[0],
  768. str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]),
  769. $sql, $c),
  770. $matches, PREG_OFFSET_CAPTURE);
  771. // Bind values' count must match the count of markers in the query
  772. if ($bind_count !== $c)
  773. {
  774. return $sql;
  775. }
  776. }
  777. elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count)
  778. {
  779. return $sql;
  780. }
  781. do
  782. {
  783. $c--;
  784. $sql = substr_replace($sql, $this->escape($binds[$c]), $matches[0][$c][1], $ml);
  785. }
  786. while ($c !== 0);
  787. return $sql;
  788. }
  789. // --------------------------------------------------------------------
  790. /**
  791. * Determines if a query is a "write" type.
  792. *
  793. * @param string An SQL query string
  794. * @return bool
  795. */
  796. public function is_write_type($sql)
  797. {
  798. 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);
  799. }
  800. // --------------------------------------------------------------------
  801. /**
  802. * Calculate the aggregate query elapsed time
  803. *
  804. * @param int The number of decimal places
  805. * @return int
  806. */
  807. public function elapsed_time($decimals = 6)
  808. {
  809. return number_format($this->benchmark, $decimals);
  810. }
  811. // --------------------------------------------------------------------
  812. /**
  813. * Returns the total number of queries
  814. *
  815. * @return int
  816. */
  817. public function total_queries()
  818. {
  819. return $this->query_count;
  820. }
  821. // --------------------------------------------------------------------
  822. /**
  823. * Returns the last query that was executed
  824. *
  825. * @return string
  826. */
  827. public function last_query()
  828. {
  829. return end($this->queries);
  830. }
  831. // --------------------------------------------------------------------
  832. /**
  833. * "Smart" Escape String
  834. *
  835. * Escapes data based on type
  836. * Sets boolean and null types
  837. *
  838. * @param string
  839. * @return mixed
  840. */
  841. public function escape($str)
  842. {
  843. if (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))
  844. {
  845. return "'".$this->escape_str($str)."'";
  846. }
  847. elseif (is_bool($str))
  848. {
  849. return ($str === FALSE) ? 0 : 1;
  850. }
  851. elseif ($str === NULL)
  852. {
  853. return 'NULL';
  854. }
  855. return $str;
  856. }
  857. // --------------------------------------------------------------------
  858. /**
  859. * Escape String
  860. *
  861. * @param string $str
  862. * @param bool $like Whether or not the string will be used in a LIKE condition
  863. * @return string
  864. */
  865. public function escape_str($str, $like = FALSE)
  866. {
  867. if (is_array($str))
  868. {
  869. foreach ($str as $key => $val)
  870. {
  871. $str[$key] = $this->escape_str($val, $like);
  872. }
  873. return $str;
  874. }
  875. $str = $this->_escape_str($str);
  876. // escape LIKE condition wildcards
  877. if ($like === TRUE)
  878. {
  879. return str_replace(array($this->_like_escape_chr, '%', '_'),
  880. array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
  881. $str);
  882. }
  883. return $str;
  884. }
  885. // --------------------------------------------------------------------
  886. /**
  887. * Escape LIKE String
  888. *
  889. * Calls the individual driver for platform
  890. * specific escaping for LIKE conditions
  891. *
  892. * @param string|string[]
  893. * @return mixed
  894. */
  895. public function escape_like_str($str)
  896. {
  897. return $this->escape_str($str, TRUE);
  898. }
  899. // --------------------------------------------------------------------
  900. /**
  901. * Platform-dependant string escape
  902. *
  903. * @param string
  904. * @return string
  905. */
  906. protected function _escape_str($str)
  907. {
  908. return str_replace("'", "''", remove_invisible_characters($str));
  909. }
  910. // --------------------------------------------------------------------
  911. /**
  912. * Primary
  913. *
  914. * Retrieves the primary key. It assumes that the row in the first
  915. * position is the primary key
  916. *
  917. * @param string the table name
  918. * @return string
  919. */
  920. public function primary($table = '')
  921. {
  922. $fields = $this->list_fields($table);
  923. return is_array($fields) ? current($fields) : FALSE;
  924. }
  925. // --------------------------------------------------------------------
  926. /**
  927. * "Count All" query
  928. *
  929. * Generates a platform-specific query string that counts all records in
  930. * the specified database
  931. *
  932. * @param string
  933. * @return int
  934. */
  935. public function count_all($table = '')
  936. {
  937. if ($table === '')
  938. {
  939. return 0;
  940. }
  941. $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
  942. if ($query->num_rows() === 0)
  943. {
  944. return 0;
  945. }
  946. $query = $query->row();
  947. $this->_reset_select();
  948. return (int) $query->numrows;
  949. }
  950. // --------------------------------------------------------------------
  951. /**
  952. * Returns an array of table names
  953. *
  954. * @param string $constrain_by_prefix = FALSE
  955. * @return array
  956. */
  957. public function list_tables($constrain_by_prefix = FALSE)
  958. {
  959. // Is there a cached result?
  960. if (isset($this->data_cache['table_names']))
  961. {
  962. return $this->data_cache['table_names'];
  963. }
  964. if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
  965. {
  966. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  967. }
  968. $this->data_cache['table_names'] = array();
  969. $query = $this->query($sql);
  970. foreach ($query->result_array() as $row)
  971. {
  972. // Do we know from which column to get the table name?
  973. if ( ! isset($key))
  974. {
  975. if (isset($row['table_name']))
  976. {
  977. $key = 'table_name';
  978. }
  979. elseif (isset($row['TABLE_NAME']))
  980. {
  981. $key = 'TABLE_NAME';
  982. }
  983. else
  984. {
  985. /* We have no other choice but to just get the first element's key.
  986. * Due to array_shift() accepting its argument by reference, if
  987. * E_STRICT is on, this would trigger a warning. So we'll have to
  988. * assign it first.
  989. */
  990. $key = array_keys($row);
  991. $key = array_shift($key);
  992. }
  993. }
  994. $this->data_cache['table_names'][] = $row[$key];
  995. }
  996. return $this->data_cache['table_names'];
  997. }
  998. // --------------------------------------------------------------------
  999. /**
  1000. * Determine if a particular table exists
  1001. *
  1002. * @param string $table_name
  1003. * @return bool
  1004. */
  1005. public function table_exists($table_name)
  1006. {
  1007. return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables());
  1008. }
  1009. // --------------------------------------------------------------------
  1010. /**
  1011. * Fetch Field Names
  1012. *
  1013. * @param string the table name
  1014. * @return array
  1015. */
  1016. public function list_fields($table = '')
  1017. {
  1018. // Is there a cached result?
  1019. if (isset($this->data_cache['field_names'][$table]))
  1020. {
  1021. return $this->data_cache['field_names'][$table];
  1022. }
  1023. if ($table === '')
  1024. {
  1025. return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
  1026. }
  1027. if (FALSE === ($sql = $this->_list_columns($table)))
  1028. {
  1029. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1030. }
  1031. $query = $this->query($sql);
  1032. $this->data_cache['field_names'][$table] = array();
  1033. foreach ($query->result_array() as $row)
  1034. {
  1035. // Do we know from where to get the column's name?
  1036. if ( ! isset($key))
  1037. {
  1038. if (isset($row['column_name']))
  1039. {
  1040. $key = 'column_name';
  1041. }
  1042. elseif (isset($row['COLUMN_NAME']))
  1043. {
  1044. $key = 'COLUMN_NAME';
  1045. }
  1046. else
  1047. {
  1048. // We have no other choice but to just get the first element's key.
  1049. $key = key($row);
  1050. }
  1051. }
  1052. $this->data_cache['field_names'][$table][] = $row[$key];
  1053. }
  1054. return $this->data_cache['field_names'][$table];
  1055. }
  1056. // --------------------------------------------------------------------
  1057. /**
  1058. * Determine if a particular field exists
  1059. *
  1060. * @param string
  1061. * @param string
  1062. * @return bool
  1063. */
  1064. public function field_exists($field_name, $table_name)
  1065. {
  1066. return in_array($field_name, $this->list_fields($table_name));
  1067. }
  1068. // --------------------------------------------------------------------
  1069. /**
  1070. * Returns an object with field data
  1071. *
  1072. * @param string the table name
  1073. * @return object
  1074. */
  1075. public function field_data($table = '')
  1076. {
  1077. if ($table === '')
  1078. {
  1079. return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
  1080. }
  1081. $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
  1082. return $query->field_data();
  1083. }
  1084. // --------------------------------------------------------------------
  1085. /**
  1086. * Escape the SQL Identifiers
  1087. *
  1088. * This function escapes column and table names
  1089. *
  1090. * @param mixed
  1091. * @return mixed
  1092. */
  1093. public function escape_identifiers($item)
  1094. {
  1095. if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers))
  1096. {
  1097. return $item;
  1098. }
  1099. elseif (is_array($item))
  1100. {
  1101. foreach ($item as $key => $value)
  1102. {
  1103. $item[$key] = $this->escape_identifiers($value);
  1104. }
  1105. return $item;
  1106. }
  1107. // Avoid breaking functions and literal values inside queries
  1108. elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE)
  1109. {
  1110. return $item;
  1111. }
  1112. static $preg_ec = array();
  1113. if (empty($preg_ec))
  1114. {
  1115. if (is_array($this->_escape_char))
  1116. {
  1117. $preg_ec = array(
  1118. preg_quote($this->_escape_char[0], '/'), preg_quote($this->_escape_char[1], '/'),
  1119. $this->_escape_char[0], $this->_escape_char[1]
  1120. );
  1121. }
  1122. else
  1123. {
  1124. $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/');
  1125. $preg_ec[2] = $preg_ec[3] = $this->_escape_char;
  1126. }
  1127. }
  1128. foreach ($this->_reserved_identifiers as $id)
  1129. {
  1130. if (strpos($item, '.'.$id) !== FALSE)
  1131. {
  1132. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item);
  1133. }
  1134. }
  1135. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item);
  1136. }
  1137. // --------------------------------------------------------------------
  1138. /**
  1139. * Generate an insert string
  1140. *
  1141. * @param string the table upon which the query will be performed
  1142. * @param array an associative array data of key/values
  1143. * @return string
  1144. */
  1145. public function insert_string($table, $data)
  1146. {
  1147. $fields = $values = array();
  1148. foreach ($data as $key => $val)
  1149. {
  1150. $fields[] = $this->escape_identifiers($key);
  1151. $values[] = $this->escape($val);
  1152. }
  1153. return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  1154. }
  1155. // --------------------------------------------------------------------
  1156. /**
  1157. * Insert statement
  1158. *
  1159. * Generates a platform-specific insert string from the supplied data
  1160. *
  1161. * @param string the table name
  1162. * @param array the insert keys
  1163. * @param array the insert values
  1164. * @return string
  1165. */
  1166. protected function _insert($table, $keys, $values)
  1167. {
  1168. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1169. }
  1170. // --------------------------------------------------------------------
  1171. /**
  1172. * Generate an update string
  1173. *
  1174. * @param string the table upon which the query will be performed
  1175. * @param array an associative array data of key/values
  1176. * @param mixed the "where" statement
  1177. * @return string
  1178. */
  1179. public function update_string($table, $data, $where)
  1180. {
  1181. if (empty($where))
  1182. {
  1183. return FALSE;
  1184. }
  1185. $this->where($where);
  1186. $fields = array();
  1187. foreach ($data as $key => $val)
  1188. {
  1189. $fields[$this->protect_identifiers($key)] = $this->escape($val);
  1190. }
  1191. $sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields);
  1192. $this->_reset_write();
  1193. return $sql;
  1194. }
  1195. // --------------------------------------------------------------------
  1196. /**
  1197. * Update statement
  1198. *
  1199. * Generates a platform-specific update string from the supplied data
  1200. *
  1201. * @param string the table name
  1202. * @param array the update data
  1203. * @return string
  1204. */
  1205. protected function _update($table, $values)
  1206. {
  1207. foreach ($values as $key => $val)
  1208. {
  1209. $valstr[] = $key.' = '.$val;
  1210. }
  1211. return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
  1212. .$this->_compile_wh('qb_where')
  1213. .$this->_compile_order_by()
  1214. .($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
  1215. }
  1216. // --------------------------------------------------------------------
  1217. /**
  1218. * Tests whether the string has an SQL operator
  1219. *
  1220. * @param string
  1221. * @return bool
  1222. */
  1223. protected function _has_operator($str)
  1224. {
  1225. return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
  1226. }
  1227. // --------------------------------------------------------------------
  1228. /**
  1229. * Returns the SQL string operator
  1230. *
  1231. * @param string
  1232. * @return string
  1233. */
  1234. protected function _get_operator($str)
  1235. {
  1236. static $_operators;
  1237. if (empty($_operators))
  1238. {
  1239. $_les = ($this->_like_escape_str !== '')
  1240. ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/')
  1241. : '';
  1242. $_operators = array(
  1243. '\s*(?:<|>|!)?=\s*', // =, <=, >=, !=
  1244. '\s*<>?\s*', // <, <>
  1245. '\s*>\s*', // >
  1246. '\s+IS NULL', // IS NULL
  1247. '\s+IS NOT NULL', // IS NOT NULL
  1248. '\s+BETWEEN\s+\S+\s+AND\s+\S+', // BETWEEN value AND value
  1249. '\s+IN\s*\([^\)]+\)', // IN(list)
  1250. '\s+NOT IN\s*\([^\)]+\)', // NOT IN (list)
  1251. '\s+LIKE\s+\S+'.$_les, // LIKE 'expr'[ ESCAPE '%s']
  1252. '\s+NOT LIKE\s+\S+'.$_les // NOT LIKE 'expr'[ ESCAPE '%s']
  1253. );
  1254. }
  1255. return preg_match('/'.implode('|', $_operators).'/i', $str, $match)
  1256. ? $match[0] : FALSE;
  1257. }
  1258. // --------------------------------------------------------------------
  1259. /**
  1260. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  1261. *
  1262. * @param string $function Function name
  1263. * @return mixed
  1264. */
  1265. public function call_function($function)
  1266. {
  1267. $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
  1268. if (FALSE === strpos($driver, $function))
  1269. {
  1270. $function = $driver.$function;
  1271. }
  1272. if ( ! function_exists($function))
  1273. {
  1274. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1275. }
  1276. return (func_num_args() > 1)
  1277. ? call_user_func_array($function, array_splice(func_get_args(), 1))
  1278. : call_user_func($function);
  1279. }
  1280. // --------------------------------------------------------------------
  1281. /**
  1282. * Set Cache Directory Path
  1283. *
  1284. * @param string the path to the cache directory
  1285. * @return void
  1286. */
  1287. public function cache_set_path($path = '')
  1288. {
  1289. $this->cachedir = $path;
  1290. }
  1291. // --------------------------------------------------------------------
  1292. /**
  1293. * Enable Query Caching
  1294. *
  1295. * @return bool cache_on value
  1296. */
  1297. public function cache_on()
  1298. {
  1299. return $this->cache_on = TRUE;
  1300. }
  1301. // --------------------------------------------------------------------
  1302. /**
  1303. * Disable Query Caching
  1304. *
  1305. * @return bool cache_on value
  1306. */
  1307. public function cache_off()
  1308. {
  1309. return $this->cache_on = FALSE;
  1310. }
  1311. // --------------------------------------------------------------------
  1312. /**
  1313. * Delete the cache files associated with a particular URI
  1314. *
  1315. * @param string $segment_one = ''
  1316. * @param string $segment_two = ''
  1317. * @return bool
  1318. */
  1319. public function cache_delete($segment_one = '', $segment_two = '')
  1320. {
  1321. return ($this->_cache_init())
  1322. ? $this->CACHE->delete($segment_one, $segment_two)
  1323. : FALSE;
  1324. }
  1325. // --------------------------------------------------------------------
  1326. /**
  1327. * Delete All cache files
  1328. *
  1329. * @return bool
  1330. */
  1331. public function cache_delete_all()
  1332. {
  1333. return ($this->_cache_init())
  1334. ? $this->CACHE->delete_all()
  1335. : FALSE;
  1336. }
  1337. // --------------------------------------------------------------------
  1338. /**
  1339. * Initialize the Cache Class
  1340. *
  1341. * @return bool
  1342. */
  1343. protected function _cache_init()
  1344. {
  1345. if (class_exists('CI_DB_Cache', FALSE))
  1346. {
  1347. if (is_object($this->CACHE))
  1348. {
  1349. return TRUE;
  1350. }
  1351. }
  1352. elseif ( ! @include_once(BASEPATH.'database/DB_cache.php'))
  1353. {
  1354. return $this->cache_off();
  1355. }
  1356. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  1357. return TRUE;
  1358. }
  1359. // --------------------------------------------------------------------
  1360. /**
  1361. * Close DB Connection
  1362. *
  1363. * @return void
  1364. */
  1365. public function close()
  1366. {
  1367. if ($this->conn_id)
  1368. {
  1369. $this->_close();
  1370. $this->conn_id = FALSE;
  1371. }
  1372. }
  1373. // --------------------------------------------------------------------
  1374. /**
  1375. * Close DB Connection
  1376. *
  1377. * This method would be overriden by most of the drivers.
  1378. *
  1379. * @return void
  1380. */
  1381. protected function _close()
  1382. {
  1383. $this->conn_id = FALSE;
  1384. }
  1385. // --------------------------------------------------------------------
  1386. /**
  1387. * Display an error message
  1388. *
  1389. * @param string the error message
  1390. * @param string any "swap" values
  1391. * @param bool whether to localize the message
  1392. * @return string sends the application/views/errors/error_db.php template
  1393. */
  1394. public function display_error($error = '', $swap = '', $native = FALSE)
  1395. {
  1396. $LANG =& load_class('Lang', 'core');
  1397. $LANG->load('db');
  1398. $heading = $LANG->line('db_error_heading');
  1399. if ($native === TRUE)
  1400. {
  1401. $message = (array) $error;
  1402. }
  1403. else
  1404. {
  1405. $message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($error)));
  1406. }
  1407. // Find the most likely culprit of the error by going through
  1408. // the backtrace until the source file is no longer in the
  1409. // database folder.
  1410. $trace = debug_backtrace();
  1411. foreach ($trace as $call)
  1412. {
  1413. if (isset($call['file'], $call['class']))
  1414. {
  1415. // We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes
  1416. if (DIRECTORY_SEPARATOR !== '/')
  1417. {
  1418. $call['file'] = str_replace('\\', '/', $call['file']);
  1419. }
  1420. if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE)
  1421. {
  1422. // Found it - use a relative path for safety
  1423. $message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']);
  1424. $message[] = 'Line Number: '.$call['line'];
  1425. break;
  1426. }
  1427. }
  1428. }
  1429. $error =& load_class('Exceptions', 'core');
  1430. echo $error->show_error($heading, $message, 'error_db');
  1431. exit(EXIT_DATABASE);
  1432. }
  1433. // --------------------------------------------------------------------
  1434. /**
  1435. * Protect Identifiers
  1436. *
  1437. * This function is used extensively by the Query Builder class, and by
  1438. * a couple functions in this class.
  1439. * It takes a column or table name (optionally with an alias) and inserts
  1440. * the table prefix onto it. Some logic is necessary in order to deal with
  1441. * column names that include the path. Consider a query like this:
  1442. *
  1443. * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
  1444. *
  1445. * Or a query with aliasing:
  1446. *
  1447. * SELECT m.member_id, m.member_name FROM members AS m
  1448. *
  1449. * Since the column name can include up to four segments (host, DB, table, column)
  1450. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1451. * insert the table prefix (if it exists) in the proper position, and escape only
  1452. * the correct identifiers.
  1453. *
  1454. * @param string
  1455. * @param bool
  1456. * @param mixed
  1457. * @param bool
  1458. * @return string
  1459. */
  1460. public function protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1461. {
  1462. if ( ! is_bool($protect_identifiers))
  1463. {
  1464. $protect_identifiers = $this->_protect_identifiers;
  1465. }
  1466. if (is_array($item))
  1467. {
  1468. $escaped_array = array();
  1469. foreach ($item as $k => $v)
  1470. {
  1471. $escaped_array[$this->protect_identifiers($k)] = $this->protect_identifiers($v, $prefix_single, $protect_identifiers, $field_exists);
  1472. }
  1473. return $escaped_array;
  1474. }
  1475. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1476. // If a parenthesis is found we know that we do not need to
  1477. // escape the data or add a prefix. There's probably a more graceful
  1478. // way to deal with this, but I'm not thinking of it -- Rick
  1479. //
  1480. // Added exception for single quotes as well, we don't want to alter
  1481. // literal strings. -- Narf
  1482. if (strpos($item, '(') !== FALSE OR strpos($item, "'") !== FALSE)
  1483. {
  1484. return $item;
  1485. }
  1486. // Convert tabs or multiple spaces into single spaces
  1487. $item = preg_replace('/\s+/', ' ', $item);
  1488. // If the item has an alias declaration we remove it and set it aside.
  1489. // Note: strripos() is used in order to support spaces in table names
  1490. if ($offset = strripos($item, ' AS '))
  1491. {
  1492. $alias = ($protect_identifiers)
  1493. ? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4))
  1494. : substr($item, $offset);
  1495. $item = substr($item, 0, $offset);
  1496. }
  1497. elseif ($offset = strrpos($item, ' '))
  1498. {
  1499. $alias = ($protect_identifiers)
  1500. ? ' '.$this->escape_identifiers(substr($item, $offset + 1))
  1501. : substr($item, $offset);
  1502. $item = substr($item, 0, $offset);
  1503. }
  1504. else
  1505. {
  1506. $alias = '';
  1507. }
  1508. // Break the string apart if it contains periods, then insert the table prefix
  1509. // in the correct location, assuming the period doesn't indicate that we're dealing
  1510. // with an alias. While we're at it, we will escape the components
  1511. if (strpos($item, '.') !== FALSE)
  1512. {
  1513. $parts = explode('.', $item);
  1514. // Does the first segment of the exploded item match
  1515. // one of the aliases previously identified? If so,
  1516. // we have nothing more to do other than escape the item
  1517. if (in_array($parts[0], $this->qb_aliased_tables))
  1518. {
  1519. if ($protect_identifiers === TRUE)
  1520. {
  1521. foreach ($parts as $key => $val)
  1522. {
  1523. if ( ! in_array($val, $this->_reserved_identifiers))
  1524. {
  1525. $parts[$key] = $this->escape_identifiers($val);
  1526. }
  1527. }
  1528. $item = implode('.', $parts);
  1529. }
  1530. return $item.$alias;
  1531. }
  1532. // Is there a table prefix defined in the config file? If not, no need to do anything
  1533. if ($this->dbprefix !== '')
  1534. {
  1535. // We now add the table prefix based on some logic.
  1536. // Do we have 4 segments (hostname.database.table.column)?
  1537. // If so, we add the table prefix to the column name in the 3rd segment.
  1538. if (isset($parts[3]))
  1539. {
  1540. $i = 2;
  1541. }
  1542. // Do we have 3 segments (database.table.column)?
  1543. // If so, we add the table prefix to the column name in 2nd position
  1544. elseif (isset($parts[2]))
  1545. {
  1546. $i = 1;
  1547. }
  1548. // Do we have 2 segments (table.column)?
  1549. // If so, we add the table prefix to the column name in 1st segment
  1550. else
  1551. {
  1552. $i = 0;
  1553. }
  1554. // This flag is set when the supplied $item does not contain a field name.
  1555. // This can happen when this function is being called from a JOIN.
  1556. if ($field_exists === FALSE)
  1557. {
  1558. $i++;
  1559. }
  1560. // Verify table prefix and replace if necessary
  1561. if ($this->swap_pre !== '' && strpos($parts[$i], $this->swap_pre) === 0)
  1562. {
  1563. $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]);
  1564. }
  1565. // We only add the table prefix if it does not already exist
  1566. elseif (strpos($parts[$i], $this->dbprefix) !== 0)
  1567. {
  1568. $parts[$i] = $this->dbprefix.$parts[$i];
  1569. }
  1570. // Put the parts back together
  1571. $item = implode('.', $parts);
  1572. }
  1573. if ($protect_identifiers === TRUE)
  1574. {
  1575. $item = $this->escape_identifiers($item);
  1576. }
  1577. return $item.$alias;
  1578. }
  1579. // Is there a table prefix? If not, no need to insert it
  1580. if ($this->dbprefix !== '')
  1581. {
  1582. // Verify table prefix and replace if necessary
  1583. if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
  1584. {
  1585. $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
  1586. }
  1587. // Do we prefix an item with no segments?
  1588. elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
  1589. {
  1590. $item = $this->dbprefix.$item;
  1591. }
  1592. }
  1593. if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
  1594. {
  1595. $item = $this->escape_identifiers($item);
  1596. }
  1597. return $item.$alias;
  1598. }
  1599. // --------------------------------------------------------------------
  1600. /**
  1601. * Dummy method that allows Query Builder class to be disabled
  1602. * and keep count_all() working.
  1603. *
  1604. * @return void
  1605. */
  1606. protected function _reset_select()
  1607. {
  1608. }
  1609. }
  1610. /* End of file DB_driver.php */
  1611. /* Location: ./system/database/DB_driver.php */