DB_driver.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Database Driver Class
  41. *
  42. * This is the platform-independent base DB implementation class.
  43. * This class will not be called directly. Rather, the adapter
  44. * class for the specific database will extend and instantiate it.
  45. *
  46. * @package CodeIgniter
  47. * @subpackage Drivers
  48. * @category Database
  49. * @author EllisLab Dev Team
  50. * @link https://codeigniter.com/user_guide/database/
  51. */
  52. abstract class CI_DB_driver {
  53. /**
  54. * Data Source Name / Connect string
  55. *
  56. * @var string
  57. */
  58. public $dsn;
  59. /**
  60. * Username
  61. *
  62. * @var string
  63. */
  64. public $username;
  65. /**
  66. * Password
  67. *
  68. * @var string
  69. */
  70. public $password;
  71. /**
  72. * Hostname
  73. *
  74. * @var string
  75. */
  76. public $hostname;
  77. /**
  78. * Database name
  79. *
  80. * @var string
  81. */
  82. public $database;
  83. /**
  84. * Database driver
  85. *
  86. * @var string
  87. */
  88. public $dbdriver = 'mysqli';
  89. /**
  90. * Sub-driver
  91. *
  92. * @used-by CI_DB_pdo_driver
  93. * @var string
  94. */
  95. public $subdriver;
  96. /**
  97. * Table prefix
  98. *
  99. * @var string
  100. */
  101. public $dbprefix = '';
  102. /**
  103. * Character set
  104. *
  105. * @var string
  106. */
  107. public $char_set = 'utf8';
  108. /**
  109. * Collation
  110. *
  111. * @var string
  112. */
  113. public $dbcollat = 'utf8_general_ci';
  114. /**
  115. * Encryption flag/data
  116. *
  117. * @var mixed
  118. */
  119. public $encrypt = FALSE;
  120. /**
  121. * Swap Prefix
  122. *
  123. * @var string
  124. */
  125. public $swap_pre = '';
  126. /**
  127. * Database port
  128. *
  129. * @var int
  130. */
  131. public $port = NULL;
  132. /**
  133. * Persistent connection flag
  134. *
  135. * @var bool
  136. */
  137. public $pconnect = FALSE;
  138. /**
  139. * Connection ID
  140. *
  141. * @var object|resource
  142. */
  143. public $conn_id = FALSE;
  144. /**
  145. * Result ID
  146. *
  147. * @var object|resource
  148. */
  149. public $result_id = FALSE;
  150. /**
  151. * Debug flag
  152. *
  153. * Whether to display error messages.
  154. *
  155. * @var bool
  156. */
  157. public $db_debug = FALSE;
  158. /**
  159. * Benchmark time
  160. *
  161. * @var int
  162. */
  163. public $benchmark = 0;
  164. /**
  165. * Executed queries count
  166. *
  167. * @var int
  168. */
  169. public $query_count = 0;
  170. /**
  171. * Bind marker
  172. *
  173. * Character used to identify values in a prepared statement.
  174. *
  175. * @var string
  176. */
  177. public $bind_marker = '?';
  178. /**
  179. * Save queries flag
  180. *
  181. * Whether to keep an in-memory history of queries for debugging purposes.
  182. *
  183. * @var bool
  184. */
  185. public $save_queries = TRUE;
  186. /**
  187. * Queries list
  188. *
  189. * @see CI_DB_driver::$save_queries
  190. * @var string[]
  191. */
  192. public $queries = array();
  193. /**
  194. * Query times
  195. *
  196. * A list of times that queries took to execute.
  197. *
  198. * @var array
  199. */
  200. public $query_times = array();
  201. /**
  202. * Data cache
  203. *
  204. * An internal generic value cache.
  205. *
  206. * @var array
  207. */
  208. public $data_cache = array();
  209. /**
  210. * Transaction enabled flag
  211. *
  212. * @var bool
  213. */
  214. public $trans_enabled = TRUE;
  215. /**
  216. * Strict transaction mode flag
  217. *
  218. * @var bool
  219. */
  220. public $trans_strict = TRUE;
  221. /**
  222. * Transaction depth level
  223. *
  224. * @var int
  225. */
  226. protected $_trans_depth = 0;
  227. /**
  228. * Transaction status flag
  229. *
  230. * Used with transactions to determine if a rollback should occur.
  231. *
  232. * @var bool
  233. */
  234. protected $_trans_status = TRUE;
  235. /**
  236. * Transaction failure flag
  237. *
  238. * Used with transactions to determine if a transaction has failed.
  239. *
  240. * @var bool
  241. */
  242. protected $_trans_failure = FALSE;
  243. /**
  244. * Cache On flag
  245. *
  246. * @var bool
  247. */
  248. public $cache_on = FALSE;
  249. /**
  250. * Cache directory path
  251. *
  252. * @var bool
  253. */
  254. public $cachedir = '';
  255. /**
  256. * Cache auto-delete flag
  257. *
  258. * @var bool
  259. */
  260. public $cache_autodel = FALSE;
  261. /**
  262. * DB Cache object
  263. *
  264. * @see CI_DB_cache
  265. * @var object
  266. */
  267. public $CACHE;
  268. /**
  269. * Protect identifiers flag
  270. *
  271. * @var bool
  272. */
  273. protected $_protect_identifiers = TRUE;
  274. /**
  275. * List of reserved identifiers
  276. *
  277. * Identifiers that must NOT be escaped.
  278. *
  279. * @var string[]
  280. */
  281. protected $_reserved_identifiers = array('*');
  282. /**
  283. * Identifier escape character
  284. *
  285. * @var string
  286. */
  287. protected $_escape_char = '"';
  288. /**
  289. * ESCAPE statement string
  290. *
  291. * @var string
  292. */
  293. protected $_like_escape_str = " ESCAPE '%s' ";
  294. /**
  295. * ESCAPE character
  296. *
  297. * @var string
  298. */
  299. protected $_like_escape_chr = '!';
  300. /**
  301. * ORDER BY random keyword
  302. *
  303. * @var array
  304. */
  305. protected $_random_keyword = array('RAND()', 'RAND(%d)');
  306. /**
  307. * COUNT string
  308. *
  309. * @used-by CI_DB_driver::count_all()
  310. * @used-by CI_DB_query_builder::count_all_results()
  311. *
  312. * @var string
  313. */
  314. protected $_count_string = 'SELECT COUNT(*) AS ';
  315. // --------------------------------------------------------------------
  316. /**
  317. * Class constructor
  318. *
  319. * @param array $params
  320. * @return void
  321. */
  322. public function __construct($params)
  323. {
  324. if (is_array($params))
  325. {
  326. foreach ($params as $key => $val)
  327. {
  328. $this->$key = $val;
  329. }
  330. }
  331. log_message('info', 'Database Driver Class Initialized');
  332. }
  333. // --------------------------------------------------------------------
  334. /**
  335. * Initialize Database Settings
  336. *
  337. * @return bool
  338. */
  339. public function initialize()
  340. {
  341. /* If an established connection is available, then there's
  342. * no need to connect and select the database.
  343. *
  344. * Depending on the database driver, conn_id can be either
  345. * boolean TRUE, a resource or an object.
  346. */
  347. if ($this->conn_id)
  348. {
  349. return TRUE;
  350. }
  351. // ----------------------------------------------------------------
  352. // Connect to the database and set the connection ID
  353. $this->conn_id = $this->db_connect($this->pconnect);
  354. // No connection resource? Check if there is a failover else throw an error
  355. if ( ! $this->conn_id)
  356. {
  357. // Check if there is a failover set
  358. if ( ! empty($this->failover) && is_array($this->failover))
  359. {
  360. // Go over all the failovers
  361. foreach ($this->failover as $failover)
  362. {
  363. // Replace the current settings with those of the failover
  364. foreach ($failover as $key => $val)
  365. {
  366. $this->$key = $val;
  367. }
  368. // Try to connect
  369. $this->conn_id = $this->db_connect($this->pconnect);
  370. // If a connection is made break the foreach loop
  371. if ($this->conn_id)
  372. {
  373. break;
  374. }
  375. }
  376. }
  377. // We still don't have a connection?
  378. if ( ! $this->conn_id)
  379. {
  380. log_message('error', 'Unable to connect to the database');
  381. if ($this->db_debug)
  382. {
  383. $this->display_error('db_unable_to_connect');
  384. }
  385. return FALSE;
  386. }
  387. }
  388. // Now we set the character set and that's all
  389. return $this->db_set_charset($this->char_set);
  390. }
  391. // --------------------------------------------------------------------
  392. /**
  393. * DB connect
  394. *
  395. * This is just a dummy method that all drivers will override.
  396. *
  397. * @return mixed
  398. */
  399. public function db_connect()
  400. {
  401. return TRUE;
  402. }
  403. // --------------------------------------------------------------------
  404. /**
  405. * Persistent database connection
  406. *
  407. * @return mixed
  408. */
  409. public function db_pconnect()
  410. {
  411. return $this->db_connect(TRUE);
  412. }
  413. // --------------------------------------------------------------------
  414. /**
  415. * Reconnect
  416. *
  417. * Keep / reestablish the db connection if no queries have been
  418. * sent for a length of time exceeding the server's idle timeout.
  419. *
  420. * This is just a dummy method to allow drivers without such
  421. * functionality to not declare it, while others will override it.
  422. *
  423. * @return void
  424. */
  425. public function reconnect()
  426. {
  427. }
  428. // --------------------------------------------------------------------
  429. /**
  430. * Select database
  431. *
  432. * This is just a dummy method to allow drivers without such
  433. * functionality to not declare it, while others will override it.
  434. *
  435. * @return bool
  436. */
  437. public function db_select()
  438. {
  439. return TRUE;
  440. }
  441. // --------------------------------------------------------------------
  442. /**
  443. * Last error
  444. *
  445. * @return array
  446. */
  447. public function error()
  448. {
  449. return array('code' => NULL, 'message' => NULL);
  450. }
  451. // --------------------------------------------------------------------
  452. /**
  453. * Set client character set
  454. *
  455. * @param string
  456. * @return bool
  457. */
  458. public function db_set_charset($charset)
  459. {
  460. if (method_exists($this, '_db_set_charset') && ! $this->_db_set_charset($charset))
  461. {
  462. log_message('error', 'Unable to set database connection charset: '.$charset);
  463. if ($this->db_debug)
  464. {
  465. $this->display_error('db_unable_to_set_charset', $charset);
  466. }
  467. return FALSE;
  468. }
  469. return TRUE;
  470. }
  471. // --------------------------------------------------------------------
  472. /**
  473. * The name of the platform in use (mysql, mssql, etc...)
  474. *
  475. * @return string
  476. */
  477. public function platform()
  478. {
  479. return $this->dbdriver;
  480. }
  481. // --------------------------------------------------------------------
  482. /**
  483. * Database version number
  484. *
  485. * Returns a string containing the version of the database being used.
  486. * Most drivers will override this method.
  487. *
  488. * @return string
  489. */
  490. public function version()
  491. {
  492. if (isset($this->data_cache['version']))
  493. {
  494. return $this->data_cache['version'];
  495. }
  496. if (FALSE === ($sql = $this->_version()))
  497. {
  498. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  499. }
  500. $query = $this->query($sql)->row();
  501. return $this->data_cache['version'] = $query->ver;
  502. }
  503. // --------------------------------------------------------------------
  504. /**
  505. * Version number query string
  506. *
  507. * @return string
  508. */
  509. protected function _version()
  510. {
  511. return 'SELECT VERSION() AS ver';
  512. }
  513. // --------------------------------------------------------------------
  514. /**
  515. * Execute the query
  516. *
  517. * Accepts an SQL string as input and returns a result object upon
  518. * successful execution of a "read" type query. Returns boolean TRUE
  519. * upon successful execution of a "write" type query. Returns boolean
  520. * FALSE upon failure, and if the $db_debug variable is set to TRUE
  521. * will raise an error.
  522. *
  523. * @param string $sql
  524. * @param array $binds = FALSE An array of binding data
  525. * @param bool $return_object = NULL
  526. * @return mixed
  527. */
  528. public function query($sql, $binds = FALSE, $return_object = NULL)
  529. {
  530. if ($sql === '')
  531. {
  532. log_message('error', 'Invalid query: '.$sql);
  533. return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE;
  534. }
  535. elseif ( ! is_bool($return_object))
  536. {
  537. $return_object = ! $this->is_write_type($sql);
  538. }
  539. // Verify table prefix and replace if necessary
  540. if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
  541. {
  542. $sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
  543. }
  544. // Compile binds if needed
  545. if ($binds !== FALSE)
  546. {
  547. $sql = $this->compile_binds($sql, $binds);
  548. }
  549. // Is query caching enabled? If the query is a "read type"
  550. // we will load the caching class and return the previously
  551. // cached query if it exists
  552. if ($this->cache_on === TRUE && $return_object === TRUE && $this->_cache_init())
  553. {
  554. $this->load_rdriver();
  555. if (FALSE !== ($cache = $this->CACHE->read($sql)))
  556. {
  557. return $cache;
  558. }
  559. }
  560. // Save the query for debugging
  561. if ($this->save_queries === TRUE)
  562. {
  563. $this->queries[] = $sql;
  564. }
  565. // Start the Query Timer
  566. $time_start = microtime(TRUE);
  567. // Run the Query
  568. if (FALSE === ($this->result_id = $this->simple_query($sql)))
  569. {
  570. if ($this->save_queries === TRUE)
  571. {
  572. $this->query_times[] = 0;
  573. }
  574. // This will trigger a rollback if transactions are being used
  575. if ($this->_trans_depth !== 0)
  576. {
  577. $this->_trans_status = FALSE;
  578. }
  579. // Grab the error now, as we might run some additional queries before displaying the error
  580. $error = $this->error();
  581. // Log errors
  582. log_message('error', 'Query error: '.$error['message'].' - Invalid query: '.$sql);
  583. if ($this->db_debug)
  584. {
  585. // We call this function in order to roll-back queries
  586. // if transactions are enabled. If we don't call this here
  587. // the error message will trigger an exit, causing the
  588. // transactions to remain in limbo.
  589. while ($this->_trans_depth !== 0)
  590. {
  591. $trans_depth = $this->_trans_depth;
  592. $this->trans_complete();
  593. if ($trans_depth === $this->_trans_depth)
  594. {
  595. log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
  596. break;
  597. }
  598. }
  599. // Display errors
  600. return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
  601. }
  602. return FALSE;
  603. }
  604. // Stop and aggregate the query time results
  605. $time_end = microtime(TRUE);
  606. $this->benchmark += $time_end - $time_start;
  607. if ($this->save_queries === TRUE)
  608. {
  609. $this->query_times[] = $time_end - $time_start;
  610. }
  611. // Increment the query counter
  612. $this->query_count++;
  613. // Will we have a result object instantiated? If not - we'll simply return TRUE
  614. if ($return_object !== TRUE)
  615. {
  616. // If caching is enabled we'll auto-cleanup any existing files related to this particular URI
  617. if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
  618. {
  619. $this->CACHE->delete();
  620. }
  621. return TRUE;
  622. }
  623. // Load and instantiate the result driver
  624. $driver = $this->load_rdriver();
  625. $RES = new $driver($this);
  626. // Is query caching enabled? If so, we'll serialize the
  627. // result object and save it to a cache file.
  628. if ($this->cache_on === TRUE && $this->_cache_init())
  629. {
  630. // We'll create a new instance of the result object
  631. // only without the platform specific driver since
  632. // we can't use it with cached data (the query result
  633. // resource ID won't be any good once we've cached the
  634. // result object, so we'll have to compile the data
  635. // and save it)
  636. $CR = new CI_DB_result($this);
  637. $CR->result_object = $RES->result_object();
  638. $CR->result_array = $RES->result_array();
  639. $CR->num_rows = $RES->num_rows();
  640. // Reset these since cached objects can not utilize resource IDs.
  641. $CR->conn_id = NULL;
  642. $CR->result_id = NULL;
  643. $this->CACHE->write($sql, $CR);
  644. }
  645. return $RES;
  646. }
  647. // --------------------------------------------------------------------
  648. /**
  649. * Load the result drivers
  650. *
  651. * @return string the name of the result class
  652. */
  653. public function load_rdriver()
  654. {
  655. $driver = 'CI_DB_'.$this->dbdriver.'_result';
  656. if ( ! class_exists($driver, FALSE))
  657. {
  658. require_once(BASEPATH.'database/DB_result.php');
  659. require_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
  660. }
  661. return $driver;
  662. }
  663. // --------------------------------------------------------------------
  664. /**
  665. * Simple Query
  666. * This is a simplified version of the query() function. Internally
  667. * we only use it when running transaction commands since they do
  668. * not require all the features of the main query() function.
  669. *
  670. * @param string the sql query
  671. * @return mixed
  672. */
  673. public function simple_query($sql)
  674. {
  675. if ( ! $this->conn_id)
  676. {
  677. if ( ! $this->initialize())
  678. {
  679. return FALSE;
  680. }
  681. }
  682. return $this->_execute($sql);
  683. }
  684. // --------------------------------------------------------------------
  685. /**
  686. * Disable Transactions
  687. * This permits transactions to be disabled at run-time.
  688. *
  689. * @return void
  690. */
  691. public function trans_off()
  692. {
  693. $this->trans_enabled = FALSE;
  694. }
  695. // --------------------------------------------------------------------
  696. /**
  697. * Enable/disable Transaction Strict Mode
  698. *
  699. * When strict mode is enabled, if you are running multiple groups of
  700. * transactions, if one group fails all subsequent groups will be
  701. * rolled back.
  702. *
  703. * If strict mode is disabled, each group is treated autonomously,
  704. * meaning a failure of one group will not affect any others
  705. *
  706. * @param bool $mode = TRUE
  707. * @return void
  708. */
  709. public function trans_strict($mode = TRUE)
  710. {
  711. $this->trans_strict = is_bool($mode) ? $mode : TRUE;
  712. }
  713. // --------------------------------------------------------------------
  714. /**
  715. * Start Transaction
  716. *
  717. * @param bool $test_mode = FALSE
  718. * @return bool
  719. */
  720. public function trans_start($test_mode = FALSE)
  721. {
  722. if ( ! $this->trans_enabled)
  723. {
  724. return FALSE;
  725. }
  726. return $this->trans_begin($test_mode);
  727. }
  728. // --------------------------------------------------------------------
  729. /**
  730. * Complete Transaction
  731. *
  732. * @return bool
  733. */
  734. public function trans_complete()
  735. {
  736. if ( ! $this->trans_enabled)
  737. {
  738. return FALSE;
  739. }
  740. // The query() function will set this flag to FALSE in the event that a query failed
  741. if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE)
  742. {
  743. $this->trans_rollback();
  744. // If we are NOT running in strict mode, we will reset
  745. // the _trans_status flag so that subsequent groups of
  746. // transactions will be permitted.
  747. if ($this->trans_strict === FALSE)
  748. {
  749. $this->_trans_status = TRUE;
  750. }
  751. log_message('debug', 'DB Transaction Failure');
  752. return FALSE;
  753. }
  754. return $this->trans_commit();
  755. }
  756. // --------------------------------------------------------------------
  757. /**
  758. * Lets you retrieve the transaction flag to determine if it has failed
  759. *
  760. * @return bool
  761. */
  762. public function trans_status()
  763. {
  764. return $this->_trans_status;
  765. }
  766. // --------------------------------------------------------------------
  767. /**
  768. * Begin Transaction
  769. *
  770. * @param bool $test_mode
  771. * @return bool
  772. */
  773. public function trans_begin($test_mode = FALSE)
  774. {
  775. if ( ! $this->trans_enabled)
  776. {
  777. return FALSE;
  778. }
  779. // When transactions are nested we only begin/commit/rollback the outermost ones
  780. elseif ($this->_trans_depth > 0)
  781. {
  782. $this->_trans_depth++;
  783. return TRUE;
  784. }
  785. // Reset the transaction failure flag.
  786. // If the $test_mode flag is set to TRUE transactions will be rolled back
  787. // even if the queries produce a successful result.
  788. $this->_trans_failure = ($test_mode === TRUE);
  789. if ($this->_trans_begin())
  790. {
  791. $this->_trans_status = TRUE;
  792. $this->_trans_depth++;
  793. return TRUE;
  794. }
  795. return FALSE;
  796. }
  797. // --------------------------------------------------------------------
  798. /**
  799. * Commit Transaction
  800. *
  801. * @return bool
  802. */
  803. public function trans_commit()
  804. {
  805. if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
  806. {
  807. return FALSE;
  808. }
  809. // When transactions are nested we only begin/commit/rollback the outermost ones
  810. elseif ($this->_trans_depth > 1 OR $this->_trans_commit())
  811. {
  812. $this->_trans_depth--;
  813. return TRUE;
  814. }
  815. return FALSE;
  816. }
  817. // --------------------------------------------------------------------
  818. /**
  819. * Rollback Transaction
  820. *
  821. * @return bool
  822. */
  823. public function trans_rollback()
  824. {
  825. if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
  826. {
  827. return FALSE;
  828. }
  829. // When transactions are nested we only begin/commit/rollback the outermost ones
  830. elseif ($this->_trans_depth > 1 OR $this->_trans_rollback())
  831. {
  832. $this->_trans_depth--;
  833. return TRUE;
  834. }
  835. return FALSE;
  836. }
  837. // --------------------------------------------------------------------
  838. /**
  839. * Compile Bindings
  840. *
  841. * @param string the sql statement
  842. * @param array an array of bind data
  843. * @return string
  844. */
  845. public function compile_binds($sql, $binds)
  846. {
  847. if (empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
  848. {
  849. return $sql;
  850. }
  851. elseif ( ! is_array($binds))
  852. {
  853. $binds = array($binds);
  854. $bind_count = 1;
  855. }
  856. else
  857. {
  858. // Make sure we're using numeric keys
  859. $binds = array_values($binds);
  860. $bind_count = count($binds);
  861. }
  862. // We'll need the marker length later
  863. $ml = strlen($this->bind_marker);
  864. // Make sure not to replace a chunk inside a string that happens to match the bind marker
  865. if ($c = preg_match_all("/'[^']*'|\"[^\"]*\"/i", $sql, $matches))
  866. {
  867. $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i',
  868. str_replace($matches[0],
  869. str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]),
  870. $sql, $c),
  871. $matches, PREG_OFFSET_CAPTURE);
  872. // Bind values' count must match the count of markers in the query
  873. if ($bind_count !== $c)
  874. {
  875. return $sql;
  876. }
  877. }
  878. elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count)
  879. {
  880. return $sql;
  881. }
  882. do
  883. {
  884. $c--;
  885. $escaped_value = $this->escape($binds[$c]);
  886. if (is_array($escaped_value))
  887. {
  888. $escaped_value = '('.implode(',', $escaped_value).')';
  889. }
  890. $sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml);
  891. }
  892. while ($c !== 0);
  893. return $sql;
  894. }
  895. // --------------------------------------------------------------------
  896. /**
  897. * Determines if a query is a "write" type.
  898. *
  899. * @param string An SQL query string
  900. * @return bool
  901. */
  902. public function is_write_type($sql)
  903. {
  904. return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX|MERGE)\s/i', $sql);
  905. }
  906. // --------------------------------------------------------------------
  907. /**
  908. * Calculate the aggregate query elapsed time
  909. *
  910. * @param int The number of decimal places
  911. * @return string
  912. */
  913. public function elapsed_time($decimals = 6)
  914. {
  915. return number_format($this->benchmark, $decimals);
  916. }
  917. // --------------------------------------------------------------------
  918. /**
  919. * Returns the total number of queries
  920. *
  921. * @return int
  922. */
  923. public function total_queries()
  924. {
  925. return $this->query_count;
  926. }
  927. // --------------------------------------------------------------------
  928. /**
  929. * Returns the last query that was executed
  930. *
  931. * @return string
  932. */
  933. public function last_query()
  934. {
  935. return end($this->queries);
  936. }
  937. // --------------------------------------------------------------------
  938. /**
  939. * "Smart" Escape String
  940. *
  941. * Escapes data based on type
  942. * Sets boolean and null types
  943. *
  944. * @param string
  945. * @return mixed
  946. */
  947. public function escape($str)
  948. {
  949. if (is_array($str))
  950. {
  951. $str = array_map(array(&$this, 'escape'), $str);
  952. return $str;
  953. }
  954. elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))
  955. {
  956. return "'".$this->escape_str($str)."'";
  957. }
  958. elseif (is_bool($str))
  959. {
  960. return ($str === FALSE) ? 0 : 1;
  961. }
  962. elseif ($str === NULL)
  963. {
  964. return 'NULL';
  965. }
  966. return $str;
  967. }
  968. // --------------------------------------------------------------------
  969. /**
  970. * Escape String
  971. *
  972. * @param string|string[] $str Input string
  973. * @param bool $like Whether or not the string will be used in a LIKE condition
  974. * @return string
  975. */
  976. public function escape_str($str, $like = FALSE)
  977. {
  978. if (is_array($str))
  979. {
  980. foreach ($str as $key => $val)
  981. {
  982. $str[$key] = $this->escape_str($val, $like);
  983. }
  984. return $str;
  985. }
  986. $str = $this->_escape_str($str);
  987. // escape LIKE condition wildcards
  988. if ($like === TRUE)
  989. {
  990. return str_replace(
  991. array($this->_like_escape_chr, '%', '_'),
  992. array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
  993. $str
  994. );
  995. }
  996. return $str;
  997. }
  998. // --------------------------------------------------------------------
  999. /**
  1000. * Escape LIKE String
  1001. *
  1002. * Calls the individual driver for platform
  1003. * specific escaping for LIKE conditions
  1004. *
  1005. * @param string|string[]
  1006. * @return mixed
  1007. */
  1008. public function escape_like_str($str)
  1009. {
  1010. return $this->escape_str($str, TRUE);
  1011. }
  1012. // --------------------------------------------------------------------
  1013. /**
  1014. * Platform-dependent string escape
  1015. *
  1016. * @param string
  1017. * @return string
  1018. */
  1019. protected function _escape_str($str)
  1020. {
  1021. return str_replace("'", "''", remove_invisible_characters($str, FALSE));
  1022. }
  1023. // --------------------------------------------------------------------
  1024. /**
  1025. * Primary
  1026. *
  1027. * Retrieves the primary key. It assumes that the row in the first
  1028. * position is the primary key
  1029. *
  1030. * @param string $table Table name
  1031. * @return string
  1032. */
  1033. public function primary($table)
  1034. {
  1035. $fields = $this->list_fields($table);
  1036. return is_array($fields) ? current($fields) : FALSE;
  1037. }
  1038. // --------------------------------------------------------------------
  1039. /**
  1040. * "Count All" query
  1041. *
  1042. * Generates a platform-specific query string that counts all records in
  1043. * the specified database
  1044. *
  1045. * @param string
  1046. * @return int
  1047. */
  1048. public function count_all($table = '')
  1049. {
  1050. if ($table === '')
  1051. {
  1052. return 0;
  1053. }
  1054. $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
  1055. if ($query->num_rows() === 0)
  1056. {
  1057. return 0;
  1058. }
  1059. $query = $query->row();
  1060. $this->_reset_select();
  1061. return (int) $query->numrows;
  1062. }
  1063. // --------------------------------------------------------------------
  1064. /**
  1065. * Returns an array of table names
  1066. *
  1067. * @param string $constrain_by_prefix = FALSE
  1068. * @return array
  1069. */
  1070. public function list_tables($constrain_by_prefix = FALSE)
  1071. {
  1072. // Is there a cached result?
  1073. if (isset($this->data_cache['table_names']))
  1074. {
  1075. return $this->data_cache['table_names'];
  1076. }
  1077. if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
  1078. {
  1079. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1080. }
  1081. $this->data_cache['table_names'] = array();
  1082. $query = $this->query($sql);
  1083. foreach ($query->result_array() as $row)
  1084. {
  1085. // Do we know from which column to get the table name?
  1086. if ( ! isset($key))
  1087. {
  1088. if (isset($row['table_name']))
  1089. {
  1090. $key = 'table_name';
  1091. }
  1092. elseif (isset($row['TABLE_NAME']))
  1093. {
  1094. $key = 'TABLE_NAME';
  1095. }
  1096. else
  1097. {
  1098. /* We have no other choice but to just get the first element's key.
  1099. * Due to array_shift() accepting its argument by reference, if
  1100. * E_STRICT is on, this would trigger a warning. So we'll have to
  1101. * assign it first.
  1102. */
  1103. $key = array_keys($row);
  1104. $key = array_shift($key);
  1105. }
  1106. }
  1107. $this->data_cache['table_names'][] = $row[$key];
  1108. }
  1109. return $this->data_cache['table_names'];
  1110. }
  1111. // --------------------------------------------------------------------
  1112. /**
  1113. * Determine if a particular table exists
  1114. *
  1115. * @param string $table_name
  1116. * @return bool
  1117. */
  1118. public function table_exists($table_name)
  1119. {
  1120. return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables());
  1121. }
  1122. // --------------------------------------------------------------------
  1123. /**
  1124. * Fetch Field Names
  1125. *
  1126. * @param string $table Table name
  1127. * @return array
  1128. */
  1129. public function list_fields($table)
  1130. {
  1131. if (FALSE === ($sql = $this->_list_columns($table)))
  1132. {
  1133. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1134. }
  1135. $query = $this->query($sql);
  1136. $fields = array();
  1137. foreach ($query->result_array() as $row)
  1138. {
  1139. // Do we know from where to get the column's name?
  1140. if ( ! isset($key))
  1141. {
  1142. if (isset($row['column_name']))
  1143. {
  1144. $key = 'column_name';
  1145. }
  1146. elseif (isset($row['COLUMN_NAME']))
  1147. {
  1148. $key = 'COLUMN_NAME';
  1149. }
  1150. else
  1151. {
  1152. // We have no other choice but to just get the first element's key.
  1153. $key = key($row);
  1154. }
  1155. }
  1156. $fields[] = $row[$key];
  1157. }
  1158. return $fields;
  1159. }
  1160. // --------------------------------------------------------------------
  1161. /**
  1162. * Determine if a particular field exists
  1163. *
  1164. * @param string
  1165. * @param string
  1166. * @return bool
  1167. */
  1168. public function field_exists($field_name, $table_name)
  1169. {
  1170. return in_array($field_name, $this->list_fields($table_name));
  1171. }
  1172. // --------------------------------------------------------------------
  1173. /**
  1174. * Returns an object with field data
  1175. *
  1176. * @param string $table the table name
  1177. * @return array
  1178. */
  1179. public function field_data($table)
  1180. {
  1181. $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
  1182. return ($query) ? $query->field_data() : FALSE;
  1183. }
  1184. // --------------------------------------------------------------------
  1185. /**
  1186. * Escape the SQL Identifiers
  1187. *
  1188. * This function escapes column and table names
  1189. *
  1190. * @param mixed
  1191. * @return mixed
  1192. */
  1193. public function escape_identifiers($item)
  1194. {
  1195. if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers))
  1196. {
  1197. return $item;
  1198. }
  1199. elseif (is_array($item))
  1200. {
  1201. foreach ($item as $key => $value)
  1202. {
  1203. $item[$key] = $this->escape_identifiers($value);
  1204. }
  1205. return $item;
  1206. }
  1207. // Avoid breaking functions and literal values inside queries
  1208. elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE)
  1209. {
  1210. return $item;
  1211. }
  1212. static $preg_ec = array();
  1213. if (empty($preg_ec))
  1214. {
  1215. if (is_array($this->_escape_char))
  1216. {
  1217. $preg_ec = array(
  1218. preg_quote($this->_escape_char[0], '/'),
  1219. preg_quote($this->_escape_char[1], '/'),
  1220. $this->_escape_char[0],
  1221. $this->_escape_char[1]
  1222. );
  1223. }
  1224. else
  1225. {
  1226. $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/');
  1227. $preg_ec[2] = $preg_ec[3] = $this->_escape_char;
  1228. }
  1229. }
  1230. foreach ($this->_reserved_identifiers as $id)
  1231. {
  1232. if (strpos($item, '.'.$id) !== FALSE)
  1233. {
  1234. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item);
  1235. }
  1236. }
  1237. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item);
  1238. }
  1239. // --------------------------------------------------------------------
  1240. /**
  1241. * Generate an insert string
  1242. *
  1243. * @param string the table upon which the query will be performed
  1244. * @param array an associative array data of key/values
  1245. * @return string
  1246. */
  1247. public function insert_string($table, $data)
  1248. {
  1249. $fields = $values = array();
  1250. foreach ($data as $key => $val)
  1251. {
  1252. $fields[] = $this->escape_identifiers($key);
  1253. $values[] = $this->escape($val);
  1254. }
  1255. return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  1256. }
  1257. // --------------------------------------------------------------------
  1258. /**
  1259. * Insert statement
  1260. *
  1261. * Generates a platform-specific insert string from the supplied data
  1262. *
  1263. * @param string the table name
  1264. * @param array the insert keys
  1265. * @param array the insert values
  1266. * @return string
  1267. */
  1268. protected function _insert($table, $keys, $values)
  1269. {
  1270. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1271. }
  1272. // --------------------------------------------------------------------
  1273. /**
  1274. * Generate an update string
  1275. *
  1276. * @param string the table upon which the query will be performed
  1277. * @param array an associative array data of key/values
  1278. * @param mixed the "where" statement
  1279. * @return string
  1280. */
  1281. public function update_string($table, $data, $where)
  1282. {
  1283. if (empty($where))
  1284. {
  1285. return FALSE;
  1286. }
  1287. $this->where($where);
  1288. $fields = array();
  1289. foreach ($data as $key => $val)
  1290. {
  1291. $fields[$this->protect_identifiers($key)] = $this->escape($val);
  1292. }
  1293. $sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields);
  1294. $this->_reset_write();
  1295. return $sql;
  1296. }
  1297. // --------------------------------------------------------------------
  1298. /**
  1299. * Update statement
  1300. *
  1301. * Generates a platform-specific update string from the supplied data
  1302. *
  1303. * @param string the table name
  1304. * @param array the update data
  1305. * @return string
  1306. */
  1307. protected function _update($table, $values)
  1308. {
  1309. foreach ($values as $key => $val)
  1310. {
  1311. $valstr[] = $key.' = '.$val;
  1312. }
  1313. return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
  1314. .$this->_compile_wh('qb_where')
  1315. .$this->_compile_order_by()
  1316. .($this->qb_limit !== FALSE ? ' LIMIT '.$this->qb_limit : '');
  1317. }
  1318. // --------------------------------------------------------------------
  1319. /**
  1320. * Tests whether the string has an SQL operator
  1321. *
  1322. * @param string
  1323. * @return bool
  1324. */
  1325. protected function _has_operator($str)
  1326. {
  1327. return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
  1328. }
  1329. // --------------------------------------------------------------------
  1330. /**
  1331. * Returns the SQL string operator
  1332. *
  1333. * @param string
  1334. * @return string
  1335. */
  1336. protected function _get_operator($str)
  1337. {
  1338. static $_operators;
  1339. if (empty($_operators))
  1340. {
  1341. $_les = ($this->_like_escape_str !== '')
  1342. ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/')
  1343. : '';
  1344. $_operators = array(
  1345. '\s*(?:<|>|!)?=\s*', // =, <=, >=, !=
  1346. '\s*<>?\s*', // <, <>
  1347. '\s*>\s*', // >
  1348. '\s+IS NULL', // IS NULL
  1349. '\s+IS NOT NULL', // IS NOT NULL
  1350. '\s+EXISTS\s*\(.*\)', // EXISTS(sql)
  1351. '\s+NOT EXISTS\s*\(.*\)', // NOT EXISTS(sql)
  1352. '\s+BETWEEN\s+', // BETWEEN value AND value
  1353. '\s+IN\s*\(.*\)', // IN(list)
  1354. '\s+NOT IN\s*\(.*\)', // NOT IN (list)
  1355. '\s+LIKE\s+\S.*('.$_les.')?', // LIKE 'expr'[ ESCAPE '%s']
  1356. '\s+NOT LIKE\s+\S.*('.$_les.')?' // NOT LIKE 'expr'[ ESCAPE '%s']
  1357. );
  1358. }
  1359. return preg_match('/'.implode('|', $_operators).'/i', $str, $match)
  1360. ? $match[0] : FALSE;
  1361. }
  1362. // --------------------------------------------------------------------
  1363. /**
  1364. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  1365. *
  1366. * @param string $function Function name
  1367. * @return mixed
  1368. */
  1369. public function call_function($function)
  1370. {
  1371. $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
  1372. if (FALSE === strpos($driver, $function))
  1373. {
  1374. $function = $driver.$function;
  1375. }
  1376. if ( ! function_exists($function))
  1377. {
  1378. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1379. }
  1380. return (func_num_args() > 1)
  1381. ? call_user_func_array($function, array_slice(func_get_args(), 1))
  1382. : call_user_func($function);
  1383. }
  1384. // --------------------------------------------------------------------
  1385. /**
  1386. * Set Cache Directory Path
  1387. *
  1388. * @param string the path to the cache directory
  1389. * @return void
  1390. */
  1391. public function cache_set_path($path = '')
  1392. {
  1393. $this->cachedir = $path;
  1394. }
  1395. // --------------------------------------------------------------------
  1396. /**
  1397. * Enable Query Caching
  1398. *
  1399. * @return bool cache_on value
  1400. */
  1401. public function cache_on()
  1402. {
  1403. return $this->cache_on = TRUE;
  1404. }
  1405. // --------------------------------------------------------------------
  1406. /**
  1407. * Disable Query Caching
  1408. *
  1409. * @return bool cache_on value
  1410. */
  1411. public function cache_off()
  1412. {
  1413. return $this->cache_on = FALSE;
  1414. }
  1415. // --------------------------------------------------------------------
  1416. /**
  1417. * Delete the cache files associated with a particular URI
  1418. *
  1419. * @param string $segment_one = ''
  1420. * @param string $segment_two = ''
  1421. * @return bool
  1422. */
  1423. public function cache_delete($segment_one = '', $segment_two = '')
  1424. {
  1425. return $this->_cache_init()
  1426. ? $this->CACHE->delete($segment_one, $segment_two)
  1427. : FALSE;
  1428. }
  1429. // --------------------------------------------------------------------
  1430. /**
  1431. * Delete All cache files
  1432. *
  1433. * @return bool
  1434. */
  1435. public function cache_delete_all()
  1436. {
  1437. return $this->_cache_init()
  1438. ? $this->CACHE->delete_all()
  1439. : FALSE;
  1440. }
  1441. // --------------------------------------------------------------------
  1442. /**
  1443. * Initialize the Cache Class
  1444. *
  1445. * @return bool
  1446. */
  1447. protected function _cache_init()
  1448. {
  1449. if ( ! class_exists('CI_DB_Cache', FALSE))
  1450. {
  1451. require_once(BASEPATH.'database/DB_cache.php');
  1452. }
  1453. elseif (is_object($this->CACHE))
  1454. {
  1455. return TRUE;
  1456. }
  1457. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  1458. return TRUE;
  1459. }
  1460. // --------------------------------------------------------------------
  1461. /**
  1462. * Close DB Connection
  1463. *
  1464. * @return void
  1465. */
  1466. public function close()
  1467. {
  1468. if ($this->conn_id)
  1469. {
  1470. $this->_close();
  1471. $this->conn_id = FALSE;
  1472. }
  1473. }
  1474. // --------------------------------------------------------------------
  1475. /**
  1476. * Close DB Connection
  1477. *
  1478. * This method would be overridden by most of the drivers.
  1479. *
  1480. * @return void
  1481. */
  1482. protected function _close()
  1483. {
  1484. $this->conn_id = FALSE;
  1485. }
  1486. // --------------------------------------------------------------------
  1487. /**
  1488. * Display an error message
  1489. *
  1490. * @param string the error message
  1491. * @param string any "swap" values
  1492. * @param bool whether to localize the message
  1493. * @return string sends the application/views/errors/error_db.php template
  1494. */
  1495. public function display_error($error = '', $swap = '', $native = FALSE)
  1496. {
  1497. $LANG =& load_class('Lang', 'core');
  1498. $LANG->load('db');
  1499. $heading = $LANG->line('db_error_heading');
  1500. if ($native === TRUE)
  1501. {
  1502. $message = (array) $error;
  1503. }
  1504. else
  1505. {
  1506. $message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($error)));
  1507. }
  1508. // Find the most likely culprit of the error by going through
  1509. // the backtrace until the source file is no longer in the
  1510. // database folder.
  1511. $trace = debug_backtrace();
  1512. foreach ($trace as $call)
  1513. {
  1514. if (isset($call['file'], $call['class']))
  1515. {
  1516. // We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes
  1517. if (DIRECTORY_SEPARATOR !== '/')
  1518. {
  1519. $call['file'] = str_replace('\\', '/', $call['file']);
  1520. }
  1521. if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE)
  1522. {
  1523. // Found it - use a relative path for safety
  1524. $message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']);
  1525. $message[] = 'Line Number: '.$call['line'];
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. $error =& load_class('Exceptions', 'core');
  1531. echo $error->show_error($heading, $message, 'error_db');
  1532. exit(8); // EXIT_DATABASE
  1533. }
  1534. // --------------------------------------------------------------------
  1535. /**
  1536. * Protect Identifiers
  1537. *
  1538. * This function is used extensively by the Query Builder class, and by
  1539. * a couple functions in this class.
  1540. * It takes a column or table name (optionally with an alias) and inserts
  1541. * the table prefix onto it. Some logic is necessary in order to deal with
  1542. * column names that include the path. Consider a query like this:
  1543. *
  1544. * SELECT hostname.database.table.column AS c FROM hostname.database.table
  1545. *
  1546. * Or a query with aliasing:
  1547. *
  1548. * SELECT m.member_id, m.member_name FROM members AS m
  1549. *
  1550. * Since the column name can include up to four segments (host, DB, table, column)
  1551. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1552. * insert the table prefix (if it exists) in the proper position, and escape only
  1553. * the correct identifiers.
  1554. *
  1555. * @param string
  1556. * @param bool
  1557. * @param mixed
  1558. * @param bool
  1559. * @return string
  1560. */
  1561. public function protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1562. {
  1563. if ( ! is_bool($protect_identifiers))
  1564. {
  1565. $protect_identifiers = $this->_protect_identifiers;
  1566. }
  1567. if (is_array($item))
  1568. {
  1569. $escaped_array = array();
  1570. foreach ($item as $k => $v)
  1571. {
  1572. $escaped_array[$this->protect_identifiers($k)] = $this->protect_identifiers($v, $prefix_single, $protect_identifiers, $field_exists);
  1573. }
  1574. return $escaped_array;
  1575. }
  1576. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1577. // If a parenthesis is found we know that we do not need to
  1578. // escape the data or add a prefix. There's probably a more graceful
  1579. // way to deal with this, but I'm not thinking of it -- Rick
  1580. //
  1581. // Added exception for single quotes as well, we don't want to alter
  1582. // literal strings. -- Narf
  1583. if (strcspn($item, "()'") !== strlen($item))
  1584. {
  1585. return $item;
  1586. }
  1587. // Convert tabs or multiple spaces into single spaces
  1588. $item = preg_replace('/\s+/', ' ', trim($item));
  1589. // If the item has an alias declaration we remove it and set it aside.
  1590. // Note: strripos() is used in order to support spaces in table names
  1591. if ($offset = strripos($item, ' AS '))
  1592. {
  1593. $alias = ($protect_identifiers)
  1594. ? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4))
  1595. : substr($item, $offset);
  1596. $item = substr($item, 0, $offset);
  1597. }
  1598. elseif ($offset = strrpos($item, ' '))
  1599. {
  1600. $alias = ($protect_identifiers)
  1601. ? ' '.$this->escape_identifiers(substr($item, $offset + 1))
  1602. : substr($item, $offset);
  1603. $item = substr($item, 0, $offset);
  1604. }
  1605. else
  1606. {
  1607. $alias = '';
  1608. }
  1609. // Break the string apart if it contains periods, then insert the table prefix
  1610. // in the correct location, assuming the period doesn't indicate that we're dealing
  1611. // with an alias. While we're at it, we will escape the components
  1612. if (strpos($item, '.') !== FALSE)
  1613. {
  1614. $parts = explode('.', $item);
  1615. // Does the first segment of the exploded item match
  1616. // one of the aliases previously identified? If so,
  1617. // we have nothing more to do other than escape the item
  1618. //
  1619. // NOTE: The ! empty() condition prevents this method
  1620. // from breaking when QB isn't enabled.
  1621. if ( ! empty($this->qb_aliased_tables) && in_array($parts[0], $this->qb_aliased_tables))
  1622. {
  1623. if ($protect_identifiers === TRUE)
  1624. {
  1625. foreach ($parts as $key => $val)
  1626. {
  1627. if ( ! in_array($val, $this->_reserved_identifiers))
  1628. {
  1629. $parts[$key] = $this->escape_identifiers($val);
  1630. }
  1631. }
  1632. $item = implode('.', $parts);
  1633. }
  1634. return $item.$alias;
  1635. }
  1636. // Is there a table prefix defined in the config file? If not, no need to do anything
  1637. if ($this->dbprefix !== '')
  1638. {
  1639. // We now add the table prefix based on some logic.
  1640. // Do we have 4 segments (hostname.database.table.column)?
  1641. // If so, we add the table prefix to the column name in the 3rd segment.
  1642. if (isset($parts[3]))
  1643. {
  1644. $i = 2;
  1645. }
  1646. // Do we have 3 segments (database.table.column)?
  1647. // If so, we add the table prefix to the column name in 2nd position
  1648. elseif (isset($parts[2]))
  1649. {
  1650. $i = 1;
  1651. }
  1652. // Do we have 2 segments (table.column)?
  1653. // If so, we add the table prefix to the column name in 1st segment
  1654. else
  1655. {
  1656. $i = 0;
  1657. }
  1658. // This flag is set when the supplied $item does not contain a field name.
  1659. // This can happen when this function is being called from a JOIN.
  1660. if ($field_exists === FALSE)
  1661. {
  1662. $i++;
  1663. }
  1664. // dbprefix may've already been applied, with or without the identifier escaped
  1665. $ec = '(?<ec>'.preg_quote(is_array($this->_escape_char) ? $this->_escape_char[0] : $this->_escape_char).')?';
  1666. isset($ec[0]) && $ec .= '?'; // Just in case someone has disabled escaping by forcing an empty escape character
  1667. // Verify table prefix and replace if necessary
  1668. if ($this->swap_pre !== '' && preg_match('#^'.$ec.preg_quote($this->swap_pre).'#', $parts[$i]))
  1669. {
  1670. $parts[$i] = preg_replace('#^'.$ec.preg_quote($this->swap_pre).'(\S+?)#', '\\1'.$this->dbprefix.'\\2', $parts[$i]);
  1671. }
  1672. // We only add the table prefix if it does not already exist
  1673. else
  1674. {
  1675. preg_match('#^'.$ec.preg_quote($this->dbprefix).'#', $parts[$i]) OR $parts[$i] = $this->dbprefix.$parts[$i];
  1676. }
  1677. // Put the parts back together
  1678. $item = implode('.', $parts);
  1679. }
  1680. if ($protect_identifiers === TRUE)
  1681. {
  1682. $item = $this->escape_identifiers($item);
  1683. }
  1684. return $item.$alias;
  1685. }
  1686. // Is there a table prefix? If not, no need to insert it
  1687. if ($this->dbprefix !== '')
  1688. {
  1689. // Verify table prefix and replace if necessary
  1690. if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
  1691. {
  1692. $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
  1693. }
  1694. // Do we prefix an item with no segments?
  1695. elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
  1696. {
  1697. $item = $this->dbprefix.$item;
  1698. }
  1699. }
  1700. if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
  1701. {
  1702. $item = $this->escape_identifiers($item);
  1703. }
  1704. return $item.$alias;
  1705. }
  1706. // --------------------------------------------------------------------
  1707. /**
  1708. * Dummy method that allows Query Builder class to be disabled
  1709. * and keep count_all() working.
  1710. *
  1711. * @return void
  1712. */
  1713. protected function _reset_select()
  1714. {
  1715. }
  1716. }