DB_driver.php 43 KB

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