DB_driver.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  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 - 2017, 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 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://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 = '';
  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. // Is there a cached result?
  1132. if (isset($this->data_cache['field_names'][$table]))
  1133. {
  1134. return $this->data_cache['field_names'][$table];
  1135. }
  1136. if (FALSE === ($sql = $this->_list_columns($table)))
  1137. {
  1138. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1139. }
  1140. $query = $this->query($sql);
  1141. $this->data_cache['field_names'][$table] = array();
  1142. foreach ($query->result_array() as $row)
  1143. {
  1144. // Do we know from where to get the column's name?
  1145. if ( ! isset($key))
  1146. {
  1147. if (isset($row['column_name']))
  1148. {
  1149. $key = 'column_name';
  1150. }
  1151. elseif (isset($row['COLUMN_NAME']))
  1152. {
  1153. $key = 'COLUMN_NAME';
  1154. }
  1155. else
  1156. {
  1157. // We have no other choice but to just get the first element's key.
  1158. $key = key($row);
  1159. }
  1160. }
  1161. $this->data_cache['field_names'][$table][] = $row[$key];
  1162. }
  1163. return $this->data_cache['field_names'][$table];
  1164. }
  1165. // --------------------------------------------------------------------
  1166. /**
  1167. * Determine if a particular field exists
  1168. *
  1169. * @param string
  1170. * @param string
  1171. * @return bool
  1172. */
  1173. public function field_exists($field_name, $table_name)
  1174. {
  1175. return in_array($field_name, $this->list_fields($table_name));
  1176. }
  1177. // --------------------------------------------------------------------
  1178. /**
  1179. * Returns an object with field data
  1180. *
  1181. * @param string $table the table name
  1182. * @return array
  1183. */
  1184. public function field_data($table)
  1185. {
  1186. $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
  1187. return ($query) ? $query->field_data() : FALSE;
  1188. }
  1189. // --------------------------------------------------------------------
  1190. /**
  1191. * Escape the SQL Identifiers
  1192. *
  1193. * This function escapes column and table names
  1194. *
  1195. * @param mixed
  1196. * @return mixed
  1197. */
  1198. public function escape_identifiers($item)
  1199. {
  1200. if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers))
  1201. {
  1202. return $item;
  1203. }
  1204. elseif (is_array($item))
  1205. {
  1206. foreach ($item as $key => $value)
  1207. {
  1208. $item[$key] = $this->escape_identifiers($value);
  1209. }
  1210. return $item;
  1211. }
  1212. // Avoid breaking functions and literal values inside queries
  1213. elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE)
  1214. {
  1215. return $item;
  1216. }
  1217. static $preg_ec = array();
  1218. if (empty($preg_ec))
  1219. {
  1220. if (is_array($this->_escape_char))
  1221. {
  1222. $preg_ec = array(
  1223. preg_quote($this->_escape_char[0], '/'),
  1224. preg_quote($this->_escape_char[1], '/'),
  1225. $this->_escape_char[0],
  1226. $this->_escape_char[1]
  1227. );
  1228. }
  1229. else
  1230. {
  1231. $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/');
  1232. $preg_ec[2] = $preg_ec[3] = $this->_escape_char;
  1233. }
  1234. }
  1235. foreach ($this->_reserved_identifiers as $id)
  1236. {
  1237. if (strpos($item, '.'.$id) !== FALSE)
  1238. {
  1239. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item);
  1240. }
  1241. }
  1242. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item);
  1243. }
  1244. // --------------------------------------------------------------------
  1245. /**
  1246. * Generate an insert string
  1247. *
  1248. * @param string the table upon which the query will be performed
  1249. * @param array an associative array data of key/values
  1250. * @return string
  1251. */
  1252. public function insert_string($table, $data)
  1253. {
  1254. $fields = $values = array();
  1255. foreach ($data as $key => $val)
  1256. {
  1257. $fields[] = $this->escape_identifiers($key);
  1258. $values[] = $this->escape($val);
  1259. }
  1260. return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  1261. }
  1262. // --------------------------------------------------------------------
  1263. /**
  1264. * Insert statement
  1265. *
  1266. * Generates a platform-specific insert string from the supplied data
  1267. *
  1268. * @param string the table name
  1269. * @param array the insert keys
  1270. * @param array the insert values
  1271. * @return string
  1272. */
  1273. protected function _insert($table, $keys, $values)
  1274. {
  1275. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1276. }
  1277. // --------------------------------------------------------------------
  1278. /**
  1279. * Generate an update string
  1280. *
  1281. * @param string the table upon which the query will be performed
  1282. * @param array an associative array data of key/values
  1283. * @param mixed the "where" statement
  1284. * @return string
  1285. */
  1286. public function update_string($table, $data, $where)
  1287. {
  1288. if (empty($where))
  1289. {
  1290. return FALSE;
  1291. }
  1292. $this->where($where);
  1293. $fields = array();
  1294. foreach ($data as $key => $val)
  1295. {
  1296. $fields[$this->protect_identifiers($key)] = $this->escape($val);
  1297. }
  1298. $sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields);
  1299. $this->_reset_write();
  1300. return $sql;
  1301. }
  1302. // --------------------------------------------------------------------
  1303. /**
  1304. * Update statement
  1305. *
  1306. * Generates a platform-specific update string from the supplied data
  1307. *
  1308. * @param string the table name
  1309. * @param array the update data
  1310. * @return string
  1311. */
  1312. protected function _update($table, $values)
  1313. {
  1314. foreach ($values as $key => $val)
  1315. {
  1316. $valstr[] = $key.' = '.$val;
  1317. }
  1318. return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
  1319. .$this->_compile_wh('qb_where')
  1320. .$this->_compile_order_by()
  1321. .($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
  1322. }
  1323. // --------------------------------------------------------------------
  1324. /**
  1325. * Tests whether the string has an SQL operator
  1326. *
  1327. * @param string
  1328. * @return bool
  1329. */
  1330. protected function _has_operator($str)
  1331. {
  1332. return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
  1333. }
  1334. // --------------------------------------------------------------------
  1335. /**
  1336. * Returns the SQL string operator
  1337. *
  1338. * @param string
  1339. * @return string
  1340. */
  1341. protected function _get_operator($str)
  1342. {
  1343. static $_operators;
  1344. if (empty($_operators))
  1345. {
  1346. $_les = ($this->_like_escape_str !== '')
  1347. ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/')
  1348. : '';
  1349. $_operators = array(
  1350. '\s*(?:<|>|!)?=\s*', // =, <=, >=, !=
  1351. '\s*<>?\s*', // <, <>
  1352. '\s*>\s*', // >
  1353. '\s+IS NULL', // IS NULL
  1354. '\s+IS NOT NULL', // IS NOT NULL
  1355. '\s+EXISTS\s*\(.*\)', // EXISTS(sql)
  1356. '\s+NOT EXISTS\s*\(.*\)', // NOT EXISTS(sql)
  1357. '\s+BETWEEN\s+', // BETWEEN value AND value
  1358. '\s+IN\s*\(.*\)', // IN(list)
  1359. '\s+NOT IN\s*\(.*\)', // NOT IN (list)
  1360. '\s+LIKE\s+\S.*('.$_les.')?', // LIKE 'expr'[ ESCAPE '%s']
  1361. '\s+NOT LIKE\s+\S.*('.$_les.')?' // NOT LIKE 'expr'[ ESCAPE '%s']
  1362. );
  1363. }
  1364. return preg_match('/'.implode('|', $_operators).'/i', $str, $match)
  1365. ? $match[0] : FALSE;
  1366. }
  1367. // --------------------------------------------------------------------
  1368. /**
  1369. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  1370. *
  1371. * @param string $function Function name
  1372. * @return mixed
  1373. */
  1374. public function call_function($function)
  1375. {
  1376. $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
  1377. if (FALSE === strpos($driver, $function))
  1378. {
  1379. $function = $driver.$function;
  1380. }
  1381. if ( ! function_exists($function))
  1382. {
  1383. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1384. }
  1385. return (func_num_args() > 1)
  1386. ? call_user_func_array($function, array_slice(func_get_args(), 1))
  1387. : call_user_func($function);
  1388. }
  1389. // --------------------------------------------------------------------
  1390. /**
  1391. * Set Cache Directory Path
  1392. *
  1393. * @param string the path to the cache directory
  1394. * @return void
  1395. */
  1396. public function cache_set_path($path = '')
  1397. {
  1398. $this->cachedir = $path;
  1399. }
  1400. // --------------------------------------------------------------------
  1401. /**
  1402. * Enable Query Caching
  1403. *
  1404. * @return bool cache_on value
  1405. */
  1406. public function cache_on()
  1407. {
  1408. return $this->cache_on = TRUE;
  1409. }
  1410. // --------------------------------------------------------------------
  1411. /**
  1412. * Disable Query Caching
  1413. *
  1414. * @return bool cache_on value
  1415. */
  1416. public function cache_off()
  1417. {
  1418. return $this->cache_on = FALSE;
  1419. }
  1420. // --------------------------------------------------------------------
  1421. /**
  1422. * Delete the cache files associated with a particular URI
  1423. *
  1424. * @param string $segment_one = ''
  1425. * @param string $segment_two = ''
  1426. * @return bool
  1427. */
  1428. public function cache_delete($segment_one = '', $segment_two = '')
  1429. {
  1430. return $this->_cache_init()
  1431. ? $this->CACHE->delete($segment_one, $segment_two)
  1432. : FALSE;
  1433. }
  1434. // --------------------------------------------------------------------
  1435. /**
  1436. * Delete All cache files
  1437. *
  1438. * @return bool
  1439. */
  1440. public function cache_delete_all()
  1441. {
  1442. return $this->_cache_init()
  1443. ? $this->CACHE->delete_all()
  1444. : FALSE;
  1445. }
  1446. // --------------------------------------------------------------------
  1447. /**
  1448. * Initialize the Cache Class
  1449. *
  1450. * @return bool
  1451. */
  1452. protected function _cache_init()
  1453. {
  1454. if ( ! class_exists('CI_DB_Cache', FALSE))
  1455. {
  1456. require_once(BASEPATH.'database/DB_cache.php');
  1457. }
  1458. elseif (is_object($this->CACHE))
  1459. {
  1460. return TRUE;
  1461. }
  1462. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  1463. return TRUE;
  1464. }
  1465. // --------------------------------------------------------------------
  1466. /**
  1467. * Close DB Connection
  1468. *
  1469. * @return void
  1470. */
  1471. public function close()
  1472. {
  1473. if ($this->conn_id)
  1474. {
  1475. $this->_close();
  1476. $this->conn_id = FALSE;
  1477. }
  1478. }
  1479. // --------------------------------------------------------------------
  1480. /**
  1481. * Close DB Connection
  1482. *
  1483. * This method would be overridden by most of the drivers.
  1484. *
  1485. * @return void
  1486. */
  1487. protected function _close()
  1488. {
  1489. $this->conn_id = FALSE;
  1490. }
  1491. // --------------------------------------------------------------------
  1492. /**
  1493. * Display an error message
  1494. *
  1495. * @param string the error message
  1496. * @param string any "swap" values
  1497. * @param bool whether to localize the message
  1498. * @return string sends the application/views/errors/error_db.php template
  1499. */
  1500. public function display_error($error = '', $swap = '', $native = FALSE)
  1501. {
  1502. $LANG =& load_class('Lang', 'core');
  1503. $LANG->load('db');
  1504. $heading = $LANG->line('db_error_heading');
  1505. if ($native === TRUE)
  1506. {
  1507. $message = (array) $error;
  1508. }
  1509. else
  1510. {
  1511. $message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($error)));
  1512. }
  1513. // Find the most likely culprit of the error by going through
  1514. // the backtrace until the source file is no longer in the
  1515. // database folder.
  1516. $trace = debug_backtrace();
  1517. foreach ($trace as $call)
  1518. {
  1519. if (isset($call['file'], $call['class']))
  1520. {
  1521. // We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes
  1522. if (DIRECTORY_SEPARATOR !== '/')
  1523. {
  1524. $call['file'] = str_replace('\\', '/', $call['file']);
  1525. }
  1526. if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE)
  1527. {
  1528. // Found it - use a relative path for safety
  1529. $message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']);
  1530. $message[] = 'Line Number: '.$call['line'];
  1531. break;
  1532. }
  1533. }
  1534. }
  1535. $error =& load_class('Exceptions', 'core');
  1536. echo $error->show_error($heading, $message, 'error_db');
  1537. exit(8); // EXIT_DATABASE
  1538. }
  1539. // --------------------------------------------------------------------
  1540. /**
  1541. * Protect Identifiers
  1542. *
  1543. * This function is used extensively by the Query Builder class, and by
  1544. * a couple functions in this class.
  1545. * It takes a column or table name (optionally with an alias) and inserts
  1546. * the table prefix onto it. Some logic is necessary in order to deal with
  1547. * column names that include the path. Consider a query like this:
  1548. *
  1549. * SELECT hostname.database.table.column AS c FROM hostname.database.table
  1550. *
  1551. * Or a query with aliasing:
  1552. *
  1553. * SELECT m.member_id, m.member_name FROM members AS m
  1554. *
  1555. * Since the column name can include up to four segments (host, DB, table, column)
  1556. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1557. * insert the table prefix (if it exists) in the proper position, and escape only
  1558. * the correct identifiers.
  1559. *
  1560. * @param string
  1561. * @param bool
  1562. * @param mixed
  1563. * @param bool
  1564. * @return string
  1565. */
  1566. public function protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1567. {
  1568. if ( ! is_bool($protect_identifiers))
  1569. {
  1570. $protect_identifiers = $this->_protect_identifiers;
  1571. }
  1572. if (is_array($item))
  1573. {
  1574. $escaped_array = array();
  1575. foreach ($item as $k => $v)
  1576. {
  1577. $escaped_array[$this->protect_identifiers($k)] = $this->protect_identifiers($v, $prefix_single, $protect_identifiers, $field_exists);
  1578. }
  1579. return $escaped_array;
  1580. }
  1581. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1582. // If a parenthesis is found we know that we do not need to
  1583. // escape the data or add a prefix. There's probably a more graceful
  1584. // way to deal with this, but I'm not thinking of it -- Rick
  1585. //
  1586. // Added exception for single quotes as well, we don't want to alter
  1587. // literal strings. -- Narf
  1588. if (strcspn($item, "()'") !== strlen($item))
  1589. {
  1590. return $item;
  1591. }
  1592. // Convert tabs or multiple spaces into single spaces
  1593. $item = preg_replace('/\s+/', ' ', trim($item));
  1594. // If the item has an alias declaration we remove it and set it aside.
  1595. // Note: strripos() is used in order to support spaces in table names
  1596. if ($offset = strripos($item, ' AS '))
  1597. {
  1598. $alias = ($protect_identifiers)
  1599. ? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4))
  1600. : substr($item, $offset);
  1601. $item = substr($item, 0, $offset);
  1602. }
  1603. elseif ($offset = strrpos($item, ' '))
  1604. {
  1605. $alias = ($protect_identifiers)
  1606. ? ' '.$this->escape_identifiers(substr($item, $offset + 1))
  1607. : substr($item, $offset);
  1608. $item = substr($item, 0, $offset);
  1609. }
  1610. else
  1611. {
  1612. $alias = '';
  1613. }
  1614. // Break the string apart if it contains periods, then insert the table prefix
  1615. // in the correct location, assuming the period doesn't indicate that we're dealing
  1616. // with an alias. While we're at it, we will escape the components
  1617. if (strpos($item, '.') !== FALSE)
  1618. {
  1619. $parts = explode('.', $item);
  1620. // Does the first segment of the exploded item match
  1621. // one of the aliases previously identified? If so,
  1622. // we have nothing more to do other than escape the item
  1623. //
  1624. // NOTE: The ! empty() condition prevents this method
  1625. // from breaking when QB isn't enabled.
  1626. if ( ! empty($this->qb_aliased_tables) && in_array($parts[0], $this->qb_aliased_tables))
  1627. {
  1628. if ($protect_identifiers === TRUE)
  1629. {
  1630. foreach ($parts as $key => $val)
  1631. {
  1632. if ( ! in_array($val, $this->_reserved_identifiers))
  1633. {
  1634. $parts[$key] = $this->escape_identifiers($val);
  1635. }
  1636. }
  1637. $item = implode('.', $parts);
  1638. }
  1639. return $item.$alias;
  1640. }
  1641. // Is there a table prefix defined in the config file? If not, no need to do anything
  1642. if ($this->dbprefix !== '')
  1643. {
  1644. // We now add the table prefix based on some logic.
  1645. // Do we have 4 segments (hostname.database.table.column)?
  1646. // If so, we add the table prefix to the column name in the 3rd segment.
  1647. if (isset($parts[3]))
  1648. {
  1649. $i = 2;
  1650. }
  1651. // Do we have 3 segments (database.table.column)?
  1652. // If so, we add the table prefix to the column name in 2nd position
  1653. elseif (isset($parts[2]))
  1654. {
  1655. $i = 1;
  1656. }
  1657. // Do we have 2 segments (table.column)?
  1658. // If so, we add the table prefix to the column name in 1st segment
  1659. else
  1660. {
  1661. $i = 0;
  1662. }
  1663. // This flag is set when the supplied $item does not contain a field name.
  1664. // This can happen when this function is being called from a JOIN.
  1665. if ($field_exists === FALSE)
  1666. {
  1667. $i++;
  1668. }
  1669. // Verify table prefix and replace if necessary
  1670. if ($this->swap_pre !== '' && strpos($parts[$i], $this->swap_pre) === 0)
  1671. {
  1672. $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]);
  1673. }
  1674. // We only add the table prefix if it does not already exist
  1675. elseif (strpos($parts[$i], $this->dbprefix) !== 0)
  1676. {
  1677. $parts[$i] = $this->dbprefix.$parts[$i];
  1678. }
  1679. // Put the parts back together
  1680. $item = implode('.', $parts);
  1681. }
  1682. if ($protect_identifiers === TRUE)
  1683. {
  1684. $item = $this->escape_identifiers($item);
  1685. }
  1686. return $item.$alias;
  1687. }
  1688. // Is there a table prefix? If not, no need to insert it
  1689. if ($this->dbprefix !== '')
  1690. {
  1691. // Verify table prefix and replace if necessary
  1692. if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
  1693. {
  1694. $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
  1695. }
  1696. // Do we prefix an item with no segments?
  1697. elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
  1698. {
  1699. $item = $this->dbprefix.$item;
  1700. }
  1701. }
  1702. if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
  1703. {
  1704. $item = $this->escape_identifiers($item);
  1705. }
  1706. return $item.$alias;
  1707. }
  1708. // --------------------------------------------------------------------
  1709. /**
  1710. * Dummy method that allows Query Builder class to be disabled
  1711. * and keep count_all() working.
  1712. *
  1713. * @return void
  1714. */
  1715. protected function _reset_select()
  1716. {
  1717. }
  1718. }