PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/system/database/DB_driver.php

https://bitbucket.org/rzavaleta/rm-iluminacion
PHP | 1390 lines | 712 code | 202 blank | 476 comment | 123 complexity | 1ad27707001b8dcb700a85022f2bf575 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 CI_DB_driver($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');
  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. // Is query caching enabled? If the query is a "read type"
  234. // we will load the caching class and return the previously
  235. // cached query if it exists
  236. if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
  237. {
  238. if ($this->_cache_init())
  239. {
  240. $this->load_rdriver();
  241. if (FALSE !== ($cache = $this->CACHE->read($sql)))
  242. {
  243. return $cache;
  244. }
  245. }
  246. }
  247. // Compile binds if needed
  248. if ($binds !== FALSE)
  249. {
  250. $sql = $this->compile_binds($sql, $binds);
  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'.EXT);
  367. include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result'.EXT);
  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. return call_user_func_array($function, $args);
  873. }
  874. }
  875. // --------------------------------------------------------------------
  876. /**
  877. * Set Cache Directory Path
  878. *
  879. * @access public
  880. * @param string the path to the cache directory
  881. * @return void
  882. */
  883. function cache_set_path($path = '')
  884. {
  885. $this->cachedir = $path;
  886. }
  887. // --------------------------------------------------------------------
  888. /**
  889. * Enable Query Caching
  890. *
  891. * @access public
  892. * @return void
  893. */
  894. function cache_on()
  895. {
  896. $this->cache_on = TRUE;
  897. return TRUE;
  898. }
  899. // --------------------------------------------------------------------
  900. /**
  901. * Disable Query Caching
  902. *
  903. * @access public
  904. * @return void
  905. */
  906. function cache_off()
  907. {
  908. $this->cache_on = FALSE;
  909. return FALSE;
  910. }
  911. // --------------------------------------------------------------------
  912. /**
  913. * Delete the cache files associated with a particular URI
  914. *
  915. * @access public
  916. * @return void
  917. */
  918. function cache_delete($segment_one = '', $segment_two = '')
  919. {
  920. if ( ! $this->_cache_init())
  921. {
  922. return FALSE;
  923. }
  924. return $this->CACHE->delete($segment_one, $segment_two);
  925. }
  926. // --------------------------------------------------------------------
  927. /**
  928. * Delete All cache files
  929. *
  930. * @access public
  931. * @return void
  932. */
  933. function cache_delete_all()
  934. {
  935. if ( ! $this->_cache_init())
  936. {
  937. return FALSE;
  938. }
  939. return $this->CACHE->delete_all();
  940. }
  941. // --------------------------------------------------------------------
  942. /**
  943. * Initialize the Cache Class
  944. *
  945. * @access private
  946. * @return void
  947. */
  948. function _cache_init()
  949. {
  950. if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
  951. {
  952. return TRUE;
  953. }
  954. if ( ! class_exists('CI_DB_Cache'))
  955. {
  956. if ( ! @include(BASEPATH.'database/DB_cache'.EXT))
  957. {
  958. return $this->cache_off();
  959. }
  960. }
  961. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  962. return TRUE;
  963. }
  964. // --------------------------------------------------------------------
  965. /**
  966. * Close DB Connection
  967. *
  968. * @access public
  969. * @return void
  970. */
  971. function close()
  972. {
  973. if (is_resource($this->conn_id) OR is_object($this->conn_id))
  974. {
  975. $this->_close($this->conn_id);
  976. }
  977. $this->conn_id = FALSE;
  978. }
  979. // --------------------------------------------------------------------
  980. /**
  981. * Display an error message
  982. *
  983. * @access public
  984. * @param string the error message
  985. * @param string any "swap" values
  986. * @param boolean whether to localize the message
  987. * @return string sends the application/error_db.php template
  988. */
  989. function display_error($error = '', $swap = '', $native = FALSE)
  990. {
  991. $LANG =& load_class('Lang', 'core');
  992. $LANG->load('db');
  993. $heading = $LANG->line('db_error_heading');
  994. if ($native == TRUE)
  995. {
  996. $message = $error;
  997. }
  998. else
  999. {
  1000. $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
  1001. }
  1002. // Find the most likely culprit of the error by going through
  1003. // the backtrace until the source file is no longer in the
  1004. // database folder.
  1005. $trace = debug_backtrace();
  1006. foreach ($trace as $call)
  1007. {
  1008. if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE)
  1009. {
  1010. // Found it - use a relative path for safety
  1011. $message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']);
  1012. $message[] = 'Line Number: '.$call['line'];
  1013. break;
  1014. }
  1015. }
  1016. $error =& load_class('Exceptions', 'core');
  1017. echo $error->show_error($heading, $message, 'error_db');
  1018. exit;
  1019. }
  1020. // --------------------------------------------------------------------
  1021. /**
  1022. * Protect Identifiers
  1023. *
  1024. * This function adds backticks if appropriate based on db type
  1025. *
  1026. * @access private
  1027. * @param mixed the item to escape
  1028. * @return mixed the item with backticks
  1029. */
  1030. function protect_identifiers($item, $prefix_single = FALSE)
  1031. {
  1032. return $this->_protect_identifiers($item, $prefix_single);
  1033. }
  1034. // --------------------------------------------------------------------
  1035. /**
  1036. * Protect Identifiers
  1037. *
  1038. * This function is used extensively by the Active Record class, and by
  1039. * a couple functions in this class.
  1040. * It takes a column or table name (optionally with an alias) and inserts
  1041. * the table prefix onto it. Some logic is necessary in order to deal with
  1042. * column names that include the path. Consider a query like this:
  1043. *
  1044. * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
  1045. *
  1046. * Or a query with aliasing:
  1047. *
  1048. * SELECT m.member_id, m.member_name FROM members AS m
  1049. *
  1050. * Since the column name can include up to four segments (host, DB, table, column)
  1051. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1052. * insert the table prefix (if it exists) in the proper position, and escape only
  1053. * the correct identifiers.
  1054. *
  1055. * @access private
  1056. * @param string
  1057. * @param bool
  1058. * @param mixed
  1059. * @param bool
  1060. * @return string
  1061. */
  1062. function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1063. {
  1064. if ( ! is_bool($protect_identifiers))
  1065. {
  1066. $protect_identifiers = $this->_protect_identifiers;
  1067. }
  1068. if (is_array($item))
  1069. {
  1070. $escaped_array = array();
  1071. foreach ($item as $k => $v)
  1072. {
  1073. $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
  1074. }
  1075. return $escaped_array;
  1076. }
  1077. // Convert tabs or multiple spaces into single spaces
  1078. $item = preg_replace('/[\t ]+/', ' ', $item);
  1079. // If the item has an alias declaration we remove it and set it aside.
  1080. // Basically we remove everything to the right of the first space
  1081. $alias = '';
  1082. if (strpos($item, ' ') !== FALSE)
  1083. {
  1084. $alias = strstr($item, " ");
  1085. $item = substr($item, 0, - strlen($alias));
  1086. }
  1087. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1088. // If a parenthesis is found we know that we do not need to
  1089. // escape the data or add a prefix. There's probably a more graceful
  1090. // way to deal with this, but I'm not thinking of it -- Rick
  1091. if (strpos($item, '(') !== FALSE)
  1092. {
  1093. return $item.$alias;
  1094. }
  1095. // Break the string apart if it contains periods, then insert the table prefix
  1096. // in the correct location, assuming the period doesn't indicate that we're dealing
  1097. // with an alias. While we're at it, we will escape the components
  1098. if (strpos($item, '.') !== FALSE)
  1099. {
  1100. $parts = explode('.', $item);
  1101. // Does the first segment of the exploded item match
  1102. // one of the aliases previously identified? If so,
  1103. // we have nothing more to do other than escape the item
  1104. if (in_array($parts[0], $this->ar_aliased_tables))
  1105. {
  1106. if ($protect_identifiers === TRUE)
  1107. {
  1108. foreach ($parts as $key => $val)
  1109. {
  1110. if ( ! in_array($val, $this->_reserved_identifiers))
  1111. {
  1112. $parts[$key] = $this->_escape_identifiers($val);
  1113. }
  1114. }
  1115. $item = implode('.', $parts);
  1116. }
  1117. return $item.$alias;
  1118. }
  1119. // Is there a table prefix defined in the config file? If not, no need to do anything
  1120. if ($this->dbprefix != '')
  1121. {
  1122. // We now add the table prefix based on some logic.
  1123. // Do we have 4 segments (hostname.database.table.column)?
  1124. // If so, we add the table prefix to the column name in the 3rd segment.
  1125. if (isset($parts[3]))
  1126. {
  1127. $i = 2;
  1128. }
  1129. // Do we have 3 segments (database.table.column)?
  1130. // If so, we add the table prefix to the column name in 2nd position
  1131. elseif (isset($parts[2]))
  1132. {
  1133. $i = 1;
  1134. }
  1135. // Do we have 2 segments (table.column)?
  1136. // If so, we add the table prefix to the column name in 1st segment
  1137. else
  1138. {
  1139. $i = 0;
  1140. }
  1141. // This flag is set when the supplied $item does not contain a field name.
  1142. // This can happen when this function is being called from a JOIN.
  1143. if ($field_exists == FALSE)
  1144. {
  1145. $i++;
  1146. }
  1147. // Verify table prefix and replace if necessary
  1148. if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
  1149. {
  1150. $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
  1151. }
  1152. // We only add the table prefix if it does not already exist
  1153. if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
  1154. {
  1155. $parts[$i] = $this->dbprefix.$parts[$i];
  1156. }
  1157. // Put the parts back together
  1158. $item = implode('.', $parts);
  1159. }
  1160. if ($protect_identifiers === TRUE)
  1161. {
  1162. $item = $this->_escape_identifiers($item);
  1163. }
  1164. return $item.$alias;
  1165. }
  1166. // Is there a table prefix? If not, no need to insert it
  1167. if ($this->dbprefix != '')
  1168. {
  1169. // Verify table prefix and replace if necessary
  1170. if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
  1171. {
  1172. $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
  1173. }
  1174. // Do we prefix an item with no segments?
  1175. if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
  1176. {
  1177. $item = $this->dbprefix.$item;
  1178. }
  1179. }
  1180. if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
  1181. {
  1182. $item = $this->_escape_identifiers($item);
  1183. }
  1184. return $item.$alias;
  1185. }
  1186. }
  1187. /* End of file DB_driver.php */
  1188. /* Location: ./system/database/DB_driver.php */