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