DB_driver.php 32 KB

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