PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/system/database/DB_driver.php

https://bitbucket.org/nfreear/trackoer-core
PHP | 1410 lines | 725 code | 201 blank | 484 comment | 124 complexity | 4c1ea76173dc7fd2eeb6b165c1e7560a MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.1.6 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author ExpressionEngine Dev Team
  9. * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
  10. * @license http://codeigniter.com/user_guide/license.html
  11. * @link http://codeigniter.com
  12. * @since Version 1.0
  13. * @filesource
  14. */
  15. // ------------------------------------------------------------------------
  16. /**
  17. * Database Driver Class
  18. *
  19. * This is the platform-independent base DB implementation class.
  20. * This class will not be called directly. Rather, the adapter
  21. * class for the specific database will extend and instantiate it.
  22. *
  23. * @package CodeIgniter
  24. * @subpackage Drivers
  25. * @category Database
  26. * @author ExpressionEngine Dev Team
  27. * @link http://codeigniter.com/user_guide/database/
  28. */
  29. class CI_DB_driver {
  30. var $username;
  31. var $password;
  32. var $hostname;
  33. var $database;
  34. var $dbdriver = 'mysql';
  35. var $dbprefix = '';
  36. var $char_set = 'utf8';
  37. var $dbcollat = 'utf8_general_ci';
  38. var $autoinit = TRUE; // Whether to automatically initialize the DB
  39. var $swap_pre = '';
  40. var $port = '';
  41. var $pconnect = FALSE;
  42. var $conn_id = FALSE;
  43. var $result_id = FALSE;
  44. var $db_debug = FALSE;
  45. var $benchmark = 0;
  46. var $query_count = 0;
  47. var $bind_marker = '?';
  48. var $save_queries = TRUE;
  49. var $queries = array();
  50. var $query_times = array();
  51. var $data_cache = array();
  52. var $trans_enabled = TRUE;
  53. var $trans_strict = TRUE;
  54. var $_trans_depth = 0;
  55. var $_trans_status = TRUE; // Used with transactions to determine if a rollback should occur
  56. var $cache_on = FALSE;
  57. var $cachedir = '';
  58. var $cache_autodel = FALSE;
  59. var $CACHE; // The cache class object
  60. // Private variables
  61. var $_protect_identifiers = TRUE;
  62. var $_reserved_identifiers = array('*'); // Identifiers that should NOT be escaped
  63. // These are use with Oracle
  64. var $stmt_id;
  65. var $curs_id;
  66. var $limit_used;
  67. /**
  68. * Constructor. Accepts one parameter containing the database
  69. * connection settings.
  70. *
  71. * @param array
  72. */
  73. function __construct($params)
  74. {
  75. if (is_array($params))
  76. {
  77. foreach ($params as $key => $val)
  78. {
  79. $this->$key = $val;
  80. }
  81. }
  82. log_message('debug', 'Database Driver Class Initialized');
  83. }
  84. // --------------------------------------------------------------------
  85. /**
  86. * Initialize Database Settings
  87. *
  88. * @access private Called by the constructor
  89. * @param mixed
  90. * @return void
  91. */
  92. function initialize()
  93. {
  94. // If an existing connection resource is available
  95. // there is no need to connect and select the database
  96. if (is_resource($this->conn_id) OR is_object($this->conn_id))
  97. {
  98. return TRUE;
  99. }
  100. // ----------------------------------------------------------------
  101. // Connect to the database and set the connection ID
  102. $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
  103. // No connection resource? Throw an error
  104. if ( ! $this->conn_id)
  105. {
  106. log_message('error', 'Unable to connect to the database');
  107. if ($this->db_debug)
  108. {
  109. $this->display_error('db_unable_to_connect');
  110. }
  111. return FALSE;
  112. }
  113. // ----------------------------------------------------------------
  114. // Select the DB... assuming a database name is specified in the config file
  115. if ($this->database != '')
  116. {
  117. if ( ! $this->db_select())
  118. {
  119. log_message('error', 'Unable to select database: '.$this->database);
  120. if ($this->db_debug)
  121. {
  122. $this->display_error('db_unable_to_select', $this->database);
  123. }
  124. return FALSE;
  125. }
  126. else
  127. {
  128. // We've selected the DB. Now we set the character set
  129. if ( ! $this->db_set_charset($this->char_set, $this->dbcollat))
  130. {
  131. return FALSE;
  132. }
  133. return TRUE;
  134. }
  135. }
  136. return TRUE;
  137. }
  138. // --------------------------------------------------------------------
  139. /**
  140. * Set client character set
  141. *
  142. * @access public
  143. * @param string
  144. * @param string
  145. * @return resource
  146. */
  147. function db_set_charset($charset, $collation)
  148. {
  149. if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat))
  150. {
  151. log_message('error', 'Unable to set database connection charset: '.$this->char_set);
  152. if ($this->db_debug)
  153. {
  154. $this->display_error('db_unable_to_set_charset', $this->char_set);
  155. }
  156. return FALSE;
  157. }
  158. return TRUE;
  159. }
  160. // --------------------------------------------------------------------
  161. /**
  162. * The name of the platform in use (mysql, mssql, etc...)
  163. *
  164. * @access public
  165. * @return string
  166. */
  167. function platform()
  168. {
  169. return $this->dbdriver;
  170. }
  171. // --------------------------------------------------------------------
  172. /**
  173. * Database Version Number. Returns a string containing the
  174. * version of the database being used
  175. *
  176. * @access public
  177. * @return string
  178. */
  179. function version()
  180. {
  181. if (FALSE === ($sql = $this->_version()))
  182. {
  183. if ($this->db_debug)
  184. {
  185. return $this->display_error('db_unsupported_function');
  186. }
  187. return FALSE;
  188. }
  189. // Some DBs have functions that return the version, and don't run special
  190. // SQL queries per se. In these instances, just return the result.
  191. $driver_version_exceptions = array('oci8', 'sqlite', 'cubrid');
  192. if (in_array($this->dbdriver, $driver_version_exceptions))
  193. {
  194. return $sql;
  195. }
  196. else
  197. {
  198. $query = $this->query($sql);
  199. return $query->row('ver');
  200. }
  201. }
  202. // --------------------------------------------------------------------
  203. /**
  204. * Execute the query
  205. *
  206. * Accepts an SQL string as input and returns a result object upon
  207. * successful execution of a "read" type query. Returns boolean TRUE
  208. * upon successful execution of a "write" type query. Returns boolean
  209. * FALSE upon failure, and if the $db_debug variable is set to TRUE
  210. * will raise an error.
  211. *
  212. * @access public
  213. * @param string An SQL query string
  214. * @param array An array of binding data
  215. * @return mixed
  216. */
  217. function query($sql, $binds = FALSE, $return_object = TRUE)
  218. {
  219. if ($sql == '')
  220. {
  221. if ($this->db_debug)
  222. {
  223. log_message('error', 'Invalid query: '.$sql);
  224. return $this->display_error('db_invalid_query');
  225. }
  226. return FALSE;
  227. }
  228. // Verify table prefix and replace if necessary
  229. if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
  230. {
  231. $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
  232. }
  233. // Compile binds if needed
  234. if ($binds !== FALSE)
  235. {
  236. $sql = $this->compile_binds($sql, $binds);
  237. }
  238. // Is query caching enabled? If the query is a "read type"
  239. // we will load the caching class and return the previously
  240. // cached query if it exists
  241. if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
  242. {
  243. if ($this->_cache_init())
  244. {
  245. $this->load_rdriver();
  246. if (FALSE !== ($cache = $this->CACHE->read($sql)))
  247. {
  248. return $cache;
  249. }
  250. }
  251. }
  252. // Save the query for debugging
  253. if ($this->save_queries == TRUE)
  254. {
  255. $this->queries[] = $sql;
  256. }
  257. // Start the Query Timer
  258. $time_start = list($sm, $ss) = explode(' ', microtime());
  259. // Run the Query
  260. if (FALSE === ($this->result_id = $this->simple_query($sql)))
  261. {
  262. if ($this->save_queries == TRUE)
  263. {
  264. $this->query_times[] = 0;
  265. }
  266. // This will trigger a rollback if transactions are being used
  267. $this->_trans_status = FALSE;
  268. if ($this->db_debug)
  269. {
  270. // grab the error number and message now, as we might run some
  271. // additional queries before displaying the error
  272. $error_no = $this->_error_number();
  273. $error_msg = $this->_error_message();
  274. // We call this function in order to roll-back queries
  275. // if transactions are enabled. If we don't call this here
  276. // the error message will trigger an exit, causing the
  277. // transactions to remain in limbo.
  278. $this->trans_complete();
  279. // Log and display errors
  280. log_message('error', 'Query error: '.$error_msg);
  281. return $this->display_error(
  282. array(
  283. 'Error Number: '.$error_no,
  284. $error_msg,
  285. $sql
  286. )
  287. );
  288. }
  289. return FALSE;
  290. }
  291. // Stop and aggregate the query time results
  292. $time_end = list($em, $es) = explode(' ', microtime());
  293. $this->benchmark += ($em + $es) - ($sm + $ss);
  294. if ($this->save_queries == TRUE)
  295. {
  296. $this->query_times[] = ($em + $es) - ($sm + $ss);
  297. }
  298. // Increment the query counter
  299. $this->query_count++;
  300. // Was the query a "write" type?
  301. // If so we'll simply return true
  302. if ($this->is_write_type($sql) === TRUE)
  303. {
  304. // If caching is enabled we'll auto-cleanup any
  305. // existing files related to this particular URI
  306. if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
  307. {
  308. $this->CACHE->delete();
  309. }
  310. return TRUE;
  311. }
  312. // Return TRUE if we don't need to create a result object
  313. // Currently only the Oracle driver uses this when stored
  314. // procedures are used
  315. if ($return_object !== TRUE)
  316. {
  317. return TRUE;
  318. }
  319. // Load and instantiate the result driver
  320. $driver = $this->load_rdriver();
  321. $RES = new $driver();
  322. $RES->conn_id = $this->conn_id;
  323. $RES->result_id = $this->result_id;
  324. if ($this->dbdriver == 'oci8')
  325. {
  326. $RES->stmt_id = $this->stmt_id;
  327. $RES->curs_id = NULL;
  328. $RES->limit_used = $this->limit_used;
  329. $this->stmt_id = FALSE;
  330. }
  331. // oci8 vars must be set before calling this
  332. $RES->num_rows = $RES->num_rows();
  333. // Is query caching enabled? If so, we'll serialize the
  334. // result object and save it to a cache file.
  335. if ($this->cache_on == TRUE AND $this->_cache_init())
  336. {
  337. // We'll create a new instance of the result object
  338. // only without the platform specific driver since
  339. // we can't use it with cached data (the query result
  340. // resource ID won't be any good once we've cached the
  341. // result object, so we'll have to compile the data
  342. // and save it)
  343. $CR = new CI_DB_result();
  344. $CR->num_rows = $RES->num_rows();
  345. $CR->result_object = $RES->result_object();
  346. $CR->result_array = $RES->result_array();
  347. // Reset these since cached objects can not utilize resource IDs.
  348. $CR->conn_id = NULL;
  349. $CR->result_id = NULL;
  350. $this->CACHE->write($sql, $CR);
  351. }
  352. return $RES;
  353. }
  354. // --------------------------------------------------------------------
  355. /**
  356. * Load the result drivers
  357. *
  358. * @access public
  359. * @return string the name of the result class
  360. */
  361. function load_rdriver()
  362. {
  363. $driver = 'CI_DB_'.$this->dbdriver.'_result';
  364. if ( ! class_exists($driver))
  365. {
  366. include_once(BASEPATH.'database/DB_result.php');
  367. include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
  368. }
  369. return $driver;
  370. }
  371. // --------------------------------------------------------------------
  372. /**
  373. * Simple Query
  374. * This is a simplified version of the query() function. Internally
  375. * we only use it when running transaction commands since they do
  376. * not require all the features of the main query() function.
  377. *
  378. * @access public
  379. * @param string the sql query
  380. * @return mixed
  381. */
  382. function simple_query($sql)
  383. {
  384. if ( ! $this->conn_id)
  385. {
  386. $this->initialize();
  387. }
  388. return $this->_execute($sql);
  389. }
  390. // --------------------------------------------------------------------
  391. /**
  392. * Disable Transactions
  393. * This permits transactions to be disabled at run-time.
  394. *
  395. * @access public
  396. * @return void
  397. */
  398. function trans_off()
  399. {
  400. $this->trans_enabled = FALSE;
  401. }
  402. // --------------------------------------------------------------------
  403. /**
  404. * Enable/disable Transaction Strict Mode
  405. * When strict mode is enabled, if you are running multiple groups of
  406. * transactions, if one group fails all groups will be rolled back.
  407. * If strict mode is disabled, each group is treated autonomously, meaning
  408. * a failure of one group will not affect any others
  409. *
  410. * @access public
  411. * @return void
  412. */
  413. function trans_strict($mode = TRUE)
  414. {
  415. $this->trans_strict = is_bool($mode) ? $mode : TRUE;
  416. }
  417. // --------------------------------------------------------------------
  418. /**
  419. * Start Transaction
  420. *
  421. * @access public
  422. * @return void
  423. */
  424. function trans_start($test_mode = FALSE)
  425. {
  426. if ( ! $this->trans_enabled)
  427. {
  428. return FALSE;
  429. }
  430. // When transactions are nested we only begin/commit/rollback the outermost ones
  431. if ($this->_trans_depth > 0)
  432. {
  433. $this->_trans_depth += 1;
  434. return;
  435. }
  436. $this->trans_begin($test_mode);
  437. }
  438. // --------------------------------------------------------------------
  439. /**
  440. * Complete Transaction
  441. *
  442. * @access public
  443. * @return bool
  444. */
  445. function trans_complete()
  446. {
  447. if ( ! $this->trans_enabled)
  448. {
  449. return FALSE;
  450. }
  451. // When transactions are nested we only begin/commit/rollback the outermost ones
  452. if ($this->_trans_depth > 1)
  453. {
  454. $this->_trans_depth -= 1;
  455. return TRUE;
  456. }
  457. // The query() function will set this flag to FALSE in the event that a query failed
  458. if ($this->_trans_status === FALSE)
  459. {
  460. $this->trans_rollback();
  461. // If we are NOT running in strict mode, we will reset
  462. // the _trans_status flag so that subsequent groups of transactions
  463. // will be permitted.
  464. if ($this->trans_strict === FALSE)
  465. {
  466. $this->_trans_status = TRUE;
  467. }
  468. log_message('debug', 'DB Transaction Failure');
  469. return FALSE;
  470. }
  471. $this->trans_commit();
  472. return TRUE;
  473. }
  474. // --------------------------------------------------------------------
  475. /**
  476. * Lets you retrieve the transaction flag to determine if it has failed
  477. *
  478. * @access public
  479. * @return bool
  480. */
  481. function trans_status()
  482. {
  483. return $this->_trans_status;
  484. }
  485. // --------------------------------------------------------------------
  486. /**
  487. * Compile Bindings
  488. *
  489. * @access public
  490. * @param string the sql statement
  491. * @param array an array of bind data
  492. * @return string
  493. */
  494. function compile_binds($sql, $binds)
  495. {
  496. if (strpos($sql, $this->bind_marker) === FALSE)
  497. {
  498. return $sql;
  499. }
  500. if ( ! is_array($binds))
  501. {
  502. $binds = array($binds);
  503. }
  504. // Get the sql segments around the bind markers
  505. $segments = explode($this->bind_marker, $sql);
  506. // The count of bind should be 1 less then the count of segments
  507. // If there are more bind arguments trim it down
  508. if (count($binds) >= count($segments)) {
  509. $binds = array_slice($binds, 0, count($segments)-1);
  510. }
  511. // Construct the binded query
  512. $result = $segments[0];
  513. $i = 0;
  514. foreach ($binds as $bind)
  515. {
  516. $result .= $this->escape($bind);
  517. $result .= $segments[++$i];
  518. }
  519. return $result;
  520. }
  521. // --------------------------------------------------------------------
  522. /**
  523. * Determines if a query is a "write" type.
  524. *
  525. * @access public
  526. * @param string An SQL query string
  527. * @return boolean
  528. */
  529. function is_write_type($sql)
  530. {
  531. if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
  532. {
  533. return FALSE;
  534. }
  535. return TRUE;
  536. }
  537. // --------------------------------------------------------------------
  538. /**
  539. * Calculate the aggregate query elapsed time
  540. *
  541. * @access public
  542. * @param integer The number of decimal places
  543. * @return integer
  544. */
  545. function elapsed_time($decimals = 6)
  546. {
  547. return number_format($this->benchmark, $decimals);
  548. }
  549. // --------------------------------------------------------------------
  550. /**
  551. * Returns the total number of queries
  552. *
  553. * @access public
  554. * @return integer
  555. */
  556. function total_queries()
  557. {
  558. return $this->query_count;
  559. }
  560. // --------------------------------------------------------------------
  561. /**
  562. * Returns the last query that was executed
  563. *
  564. * @access public
  565. * @return void
  566. */
  567. function last_query()
  568. {
  569. return end($this->queries);
  570. }
  571. // --------------------------------------------------------------------
  572. /**
  573. * "Smart" Escape String
  574. *
  575. * Escapes data based on type
  576. * Sets boolean and null types
  577. *
  578. * @access public
  579. * @param string
  580. * @return mixed
  581. */
  582. function escape($str)
  583. {
  584. if (is_string($str))
  585. {
  586. $str = "'".$this->escape_str($str)."'";
  587. }
  588. elseif (is_bool($str))
  589. {
  590. $str = ($str === FALSE) ? 0 : 1;
  591. }
  592. elseif (is_null($str))
  593. {
  594. $str = 'NULL';
  595. }
  596. return $str;
  597. }
  598. // --------------------------------------------------------------------
  599. /**
  600. * Escape LIKE String
  601. *
  602. * Calls the individual driver for platform
  603. * specific escaping for LIKE conditions
  604. *
  605. * @access public
  606. * @param string
  607. * @return mixed
  608. */
  609. function escape_like_str($str)
  610. {
  611. return $this->escape_str($str, TRUE);
  612. }
  613. // --------------------------------------------------------------------
  614. /**
  615. * Primary
  616. *
  617. * Retrieves the primary key. It assumes that the row in the first
  618. * position is the primary key
  619. *
  620. * @access public
  621. * @param string the table name
  622. * @return string
  623. */
  624. function primary($table = '')
  625. {
  626. $fields = $this->list_fields($table);
  627. if ( ! is_array($fields))
  628. {
  629. return FALSE;
  630. }
  631. return current($fields);
  632. }
  633. // --------------------------------------------------------------------
  634. /**
  635. * Returns an array of table names
  636. *
  637. * @access public
  638. * @return array
  639. */
  640. function list_tables($constrain_by_prefix = FALSE)
  641. {
  642. // Is there a cached result?
  643. if (isset($this->data_cache['table_names']))
  644. {
  645. return $this->data_cache['table_names'];
  646. }
  647. if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
  648. {
  649. if ($this->db_debug)
  650. {
  651. return $this->display_error('db_unsupported_function');
  652. }
  653. return FALSE;
  654. }
  655. $retval = array();
  656. $query = $this->query($sql);
  657. if ($query->num_rows() > 0)
  658. {
  659. foreach ($query->result_array() as $row)
  660. {
  661. if (isset($row['TABLE_NAME']))
  662. {
  663. $retval[] = $row['TABLE_NAME'];
  664. }
  665. else
  666. {
  667. $retval[] = array_shift($row);
  668. }
  669. }
  670. }
  671. $this->data_cache['table_names'] = $retval;
  672. return $this->data_cache['table_names'];
  673. }
  674. // --------------------------------------------------------------------
  675. /**
  676. * Determine if a particular table exists
  677. * @access public
  678. * @return boolean
  679. */
  680. function table_exists($table_name)
  681. {
  682. return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE;
  683. }
  684. // --------------------------------------------------------------------
  685. /**
  686. * Fetch MySQL Field Names
  687. *
  688. * @access public
  689. * @param string the table name
  690. * @return array
  691. */
  692. function list_fields($table = '')
  693. {
  694. // Is there a cached result?
  695. if (isset($this->data_cache['field_names'][$table]))
  696. {
  697. return $this->data_cache['field_names'][$table];
  698. }
  699. if ($table == '')
  700. {
  701. if ($this->db_debug)
  702. {
  703. return $this->display_error('db_field_param_missing');
  704. }
  705. return FALSE;
  706. }
  707. if (FALSE === ($sql = $this->_list_columns($table)))
  708. {
  709. if ($this->db_debug)
  710. {
  711. return $this->display_error('db_unsupported_function');
  712. }
  713. return FALSE;
  714. }
  715. $query = $this->query($sql);
  716. $retval = array();
  717. foreach ($query->result_array() as $row)
  718. {
  719. if (isset($row['COLUMN_NAME']))
  720. {
  721. $retval[] = $row['COLUMN_NAME'];
  722. }
  723. else
  724. {
  725. $retval[] = current($row);
  726. }
  727. }
  728. $this->data_cache['field_names'][$table] = $retval;
  729. return $this->data_cache['field_names'][$table];
  730. }
  731. // --------------------------------------------------------------------
  732. /**
  733. * Determine if a particular field exists
  734. * @access public
  735. * @param string
  736. * @param string
  737. * @return boolean
  738. */
  739. function field_exists($field_name, $table_name)
  740. {
  741. return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
  742. }
  743. // --------------------------------------------------------------------
  744. /**
  745. * Returns an object with field data
  746. *
  747. * @access public
  748. * @param string the table name
  749. * @return object
  750. */
  751. function field_data($table = '')
  752. {
  753. if ($table == '')
  754. {
  755. if ($this->db_debug)
  756. {
  757. return $this->display_error('db_field_param_missing');
  758. }
  759. return FALSE;
  760. }
  761. $query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE)));
  762. return $query->field_data();
  763. }
  764. // --------------------------------------------------------------------
  765. /**
  766. * Generate an insert string
  767. *
  768. * @access public
  769. * @param string the table upon which the query will be performed
  770. * @param array an associative array data of key/values
  771. * @return string
  772. */
  773. function insert_string($table, $data)
  774. {
  775. $fields = array();
  776. $values = array();
  777. foreach ($data as $key => $val)
  778. {
  779. $fields[] = $this->_escape_identifiers($key);
  780. $values[] = $this->escape($val);
  781. }
  782. return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  783. }
  784. // --------------------------------------------------------------------
  785. /**
  786. * Generate an update string
  787. *
  788. * @access public
  789. * @param string the table upon which the query will be performed
  790. * @param array an associative array data of key/values
  791. * @param mixed the "where" statement
  792. * @return string
  793. */
  794. function update_string($table, $data, $where)
  795. {
  796. if ($where == '')
  797. {
  798. return false;
  799. }
  800. $fields = array();
  801. foreach ($data as $key => $val)
  802. {
  803. $fields[$this->_protect_identifiers($key)] = $this->escape($val);
  804. }
  805. if ( ! is_array($where))
  806. {
  807. $dest = array($where);
  808. }
  809. else
  810. {
  811. $dest = array();
  812. foreach ($where as $key => $val)
  813. {
  814. $prefix = (count($dest) == 0) ? '' : ' AND ';
  815. if ($val !== '')
  816. {
  817. if ( ! $this->_has_operator($key))
  818. {
  819. $key .= ' =';
  820. }
  821. $val = ' '.$this->escape($val);
  822. }
  823. $dest[] = $prefix.$key.$val;
  824. }
  825. }
  826. return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest);
  827. }
  828. // --------------------------------------------------------------------
  829. /**
  830. * Tests whether the string has an SQL operator
  831. *
  832. * @access private
  833. * @param string
  834. * @return bool
  835. */
  836. function _has_operator($str)
  837. {
  838. $str = trim($str);
  839. if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
  840. {
  841. return FALSE;
  842. }
  843. return TRUE;
  844. }
  845. // --------------------------------------------------------------------
  846. /**
  847. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  848. *
  849. * @access public
  850. * @param string the function name
  851. * @param mixed any parameters needed by the function
  852. * @return mixed
  853. */
  854. function call_function($function)
  855. {
  856. $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
  857. if (FALSE === strpos($driver, $function))
  858. {
  859. $function = $driver.$function;
  860. }
  861. if ( ! function_exists($function))
  862. {
  863. if ($this->db_debug)
  864. {
  865. return $this->display_error('db_unsupported_function');
  866. }
  867. return FALSE;
  868. }
  869. else
  870. {
  871. $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
  872. if (is_null($args))
  873. {
  874. return call_user_func($function);
  875. }
  876. else
  877. {
  878. return call_user_func_array($function, $args);
  879. }
  880. }
  881. }
  882. // --------------------------------------------------------------------
  883. /**
  884. * Set Cache Directory Path
  885. *
  886. * @access public
  887. * @param string the path to the cache directory
  888. * @return void
  889. */
  890. function cache_set_path($path = '')
  891. {
  892. $this->cachedir = $path;
  893. }
  894. // --------------------------------------------------------------------
  895. /**
  896. * Enable Query Caching
  897. *
  898. * @access public
  899. * @return void
  900. */
  901. function cache_on()
  902. {
  903. $this->cache_on = TRUE;
  904. return TRUE;
  905. }
  906. // --------------------------------------------------------------------
  907. /**
  908. * Disable Query Caching
  909. *
  910. * @access public
  911. * @return void
  912. */
  913. function cache_off()
  914. {
  915. $this->cache_on = FALSE;
  916. return FALSE;
  917. }
  918. // --------------------------------------------------------------------
  919. /**
  920. * Delete the cache files associated with a particular URI
  921. *
  922. * @access public
  923. * @return void
  924. */
  925. function cache_delete($segment_one = '', $segment_two = '')
  926. {
  927. if ( ! $this->_cache_init())
  928. {
  929. return FALSE;
  930. }
  931. return $this->CACHE->delete($segment_one, $segment_two);
  932. }
  933. // --------------------------------------------------------------------
  934. /**
  935. * Delete All cache files
  936. *
  937. * @access public
  938. * @return void
  939. */
  940. function cache_delete_all()
  941. {
  942. if ( ! $this->_cache_init())
  943. {
  944. return FALSE;
  945. }
  946. return $this->CACHE->delete_all();
  947. }
  948. // --------------------------------------------------------------------
  949. /**
  950. * Initialize the Cache Class
  951. *
  952. * @access private
  953. * @return void
  954. */
  955. function _cache_init()
  956. {
  957. if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
  958. {
  959. return TRUE;
  960. }
  961. if ( ! class_exists('CI_DB_Cache'))
  962. {
  963. if ( ! @include(BASEPATH.'database/DB_cache.php'))
  964. {
  965. return $this->cache_off();
  966. }
  967. }
  968. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  969. return TRUE;
  970. }
  971. // --------------------------------------------------------------------
  972. /**
  973. * Close DB Connection
  974. *
  975. * @access public
  976. * @return void
  977. */
  978. function close()
  979. {
  980. if (is_resource($this->conn_id) OR is_object($this->conn_id))
  981. {
  982. $this->_close($this->conn_id);
  983. }
  984. $this->conn_id = FALSE;
  985. }
  986. // --------------------------------------------------------------------
  987. /**
  988. * Display an error message
  989. *
  990. * @access public
  991. * @param string the error message
  992. * @param string any "swap" values
  993. * @param boolean whether to localize the message
  994. * @return string sends the application/error_db.php template
  995. */
  996. function display_error($error = '', $swap = '', $native = FALSE)
  997. {
  998. $LANG =& load_class('Lang', 'core');
  999. $LANG->load('db');
  1000. $heading = $LANG->line('db_error_heading');
  1001. if ($native == TRUE)
  1002. {
  1003. $message = $error;
  1004. }
  1005. else
  1006. {
  1007. $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
  1008. }
  1009. // Find the most likely culprit of the error by going through
  1010. // the backtrace until the source file is no longer in the
  1011. // database folder.
  1012. $trace = debug_backtrace();
  1013. foreach ($trace as $call)
  1014. {
  1015. if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE)
  1016. {
  1017. // Found it - use a relative path for safety
  1018. $message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']);
  1019. $message[] = 'Line Number: '.$call['line'];
  1020. break;
  1021. }
  1022. }
  1023. $error =& load_class('Exceptions', 'core');
  1024. echo $error->show_error($heading, $message, 'error_db');
  1025. exit;
  1026. }
  1027. // --------------------------------------------------------------------
  1028. /**
  1029. * Protect Identifiers
  1030. *
  1031. * This function adds backticks if appropriate based on db type
  1032. *
  1033. * @access private
  1034. * @param mixed the item to escape
  1035. * @return mixed the item with backticks
  1036. */
  1037. function protect_identifiers($item, $prefix_single = FALSE)
  1038. {
  1039. return $this->_protect_identifiers($item, $prefix_single);
  1040. }
  1041. // --------------------------------------------------------------------
  1042. /**
  1043. * Protect Identifiers
  1044. *
  1045. * This function is used extensively by the Active Record class, and by
  1046. * a couple functions in this class.
  1047. * It takes a column or table name (optionally with an alias) and inserts
  1048. * the table prefix onto it. Some logic is necessary in order to deal with
  1049. * column names that include the path. Consider a query like this:
  1050. *
  1051. * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
  1052. *
  1053. * Or a query with aliasing:
  1054. *
  1055. * SELECT m.member_id, m.member_name FROM members AS m
  1056. *
  1057. * Since the column name can include up to four segments (host, DB, table, column)
  1058. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1059. * insert the table prefix (if it exists) in the proper position, and escape only
  1060. * the correct identifiers.
  1061. *
  1062. * @access private
  1063. * @param string
  1064. * @param bool
  1065. * @param mixed
  1066. * @param bool
  1067. * @return string
  1068. */
  1069. function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1070. {
  1071. if ( ! is_bool($protect_identifiers))
  1072. {
  1073. $protect_identifiers = $this->_protect_identifiers;
  1074. }
  1075. if (is_array($item))
  1076. {
  1077. $escaped_array = array();
  1078. foreach ($item as $k => $v)
  1079. {
  1080. $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
  1081. }
  1082. return $escaped_array;
  1083. }
  1084. // Convert tabs or multiple spaces into single spaces
  1085. $item = preg_replace('/[\t ]+/', ' ', $item);
  1086. // If the item has an alias declaration we remove it and set it aside.
  1087. // Basically we remove everything to the right of the first space
  1088. if (strpos($item, ' ') !== FALSE)
  1089. {
  1090. $alias = strstr($item, ' ');
  1091. $item = substr($item, 0, - strlen($alias));
  1092. }
  1093. else
  1094. {
  1095. $alias = '';
  1096. }
  1097. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1098. // If a parenthesis is found we know that we do not need to
  1099. // escape the data or add a prefix. There's probably a more graceful
  1100. // way to deal with this, but I'm not thinking of it -- Rick
  1101. if (strpos($item, '(') !== FALSE)
  1102. {
  1103. return $item.$alias;
  1104. }
  1105. // Break the string apart if it contains periods, then insert the table prefix
  1106. // in the correct location, assuming the period doesn't indicate that we're dealing
  1107. // with an alias. While we're at it, we will escape the components
  1108. if (strpos($item, '.') !== FALSE)
  1109. {
  1110. $parts = explode('.', $item);
  1111. // Does the first segment of the exploded item match
  1112. // one of the aliases previously identified? If so,
  1113. // we have nothing more to do other than escape the item
  1114. if (in_array($parts[0], $this->ar_aliased_tables))
  1115. {
  1116. if ($protect_identifiers === TRUE)
  1117. {
  1118. foreach ($parts as $key => $val)
  1119. {
  1120. if ( ! in_array($val, $this->_reserved_identifiers))
  1121. {
  1122. $parts[$key] = $this->_escape_identifiers($val);
  1123. }
  1124. }
  1125. $item = implode('.', $parts);
  1126. }
  1127. return $item.$alias;
  1128. }
  1129. // Is there a table prefix defined in the config file? If not, no need to do anything
  1130. if ($this->dbprefix != '')
  1131. {
  1132. // We now add the table prefix based on some logic.
  1133. // Do we have 4 segments (hostname.database.table.column)?
  1134. // If so, we add the table prefix to the column name in the 3rd segment.
  1135. if (isset($parts[3]))
  1136. {
  1137. $i = 2;
  1138. }
  1139. // Do we have 3 segments (database.table.column)?
  1140. // If so, we add the table prefix to the column name in 2nd position
  1141. elseif (isset($parts[2]))
  1142. {
  1143. $i = 1;
  1144. }
  1145. // Do we have 2 segments (table.column)?
  1146. // If so, we add the table prefix to the column name in 1st segment
  1147. else
  1148. {
  1149. $i = 0;
  1150. }
  1151. // This flag is set when the supplied $item does not contain a field name.
  1152. // This can happen when this function is being called from a JOIN.
  1153. if ($field_exists == FALSE)
  1154. {
  1155. $i++;
  1156. }
  1157. // Verify table prefix and replace if necessary
  1158. if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
  1159. {
  1160. $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
  1161. }
  1162. // We only add the table prefix if it does not already exist
  1163. if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
  1164. {
  1165. $parts[$i] = $this->dbprefix.$parts[$i];
  1166. }
  1167. // Put the parts back together
  1168. $item = implode('.', $parts);
  1169. }
  1170. if ($protect_identifiers === TRUE)
  1171. {
  1172. $item = $this->_escape_identifiers($item);
  1173. }
  1174. return $item.$alias;
  1175. }
  1176. // Is there a table prefix? If not, no need to insert it
  1177. if ($this->dbprefix != '')
  1178. {
  1179. // Verify table prefix and replace if necessary
  1180. if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
  1181. {
  1182. $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
  1183. }
  1184. // Do we prefix an item with no segments?
  1185. if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
  1186. {
  1187. $item = $this->dbprefix.$item;
  1188. }
  1189. }
  1190. if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
  1191. {
  1192. $item = $this->_escape_identifiers($item);
  1193. }
  1194. return $item.$alias;
  1195. }
  1196. // --------------------------------------------------------------------
  1197. /**
  1198. * Dummy method that allows Active Record class to be disabled
  1199. *
  1200. * This function is used extensively by every db driver.
  1201. *
  1202. * @return void
  1203. */
  1204. protected function _reset_select()
  1205. {
  1206. }
  1207. }
  1208. /* End of file DB_driver.php */
  1209. /* Location: ./system/database/DB_driver.php */