/halogy/database/DB_driver.php

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