blob: c2fa70a72c280f3cf0202eab6d8120a9e3500971 [file] [log] [blame]
Derek Allardd2df9bc2007-04-15 17:41:17 +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 Rick Ellis
9 * @copyright Copyright (c) 2006, EllisLab, Inc.
Derek Allard6838f002007-10-04 19:29:59 +000010 * @license http://www.codeigniter.com/user_guide/license.html
Derek Allardd2df9bc2007-04-15 17:41:17 +000011 * @link http://www.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 Rick Ellis
29 * @link http://www.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 = '';
Derek Allard39b622d2008-01-16 21:10:09 +000039 var $autoinit = TRUE; // Whether to automatically initialize the DB
40 var $swap_pre = '';
Derek Allardd2df9bc2007-04-15 17:41:17 +000041 var $port = '';
42 var $pconnect = FALSE;
43 var $conn_id = FALSE;
44 var $result_id = FALSE;
45 var $db_debug = FALSE;
46 var $benchmark = 0;
47 var $query_count = 0;
48 var $bind_marker = '?';
Rick Ellis40990462007-07-17 21:40:44 +000049 var $save_queries = TRUE;
Derek Allardd2df9bc2007-04-15 17:41:17 +000050 var $queries = array();
51 var $data_cache = array();
52 var $trans_enabled = TRUE;
53 var $_trans_depth = 0;
Rick Ellis28239ad2007-06-11 04:26:39 +000054 var $_trans_status = TRUE; // Used with transactions to determine if a rollback should occur
Derek Allardd2df9bc2007-04-15 17:41:17 +000055 var $cache_on = FALSE;
56 var $cachedir = '';
57 var $cache_autodel = FALSE;
58 var $CACHE; // The cache class object
59
60
61 // These are use with Oracle
62 var $stmt_id;
63 var $curs_id;
64 var $limit_used;
65
66
67
68 /**
69 * Constructor. Accepts one parameter containing the database
70 * connection settings.
71 *
72 * Database settings can be passed as discreet
73 * parameters or as a data source name in the first
74 * parameter. DSNs must have this prototype:
75 * $dsn = 'driver://username:password@hostname/database';
76 *
77 * @param mixed. Can be an array or a DSN string
78 */
79 function CI_DB_driver($params)
80 {
Derek Allardd2df9bc2007-04-15 17:41:17 +000081 if (is_array($params))
82 {
Derek Allard39b622d2008-01-16 21:10:09 +000083 foreach ($params as $key => $val)
Derek Allardd2df9bc2007-04-15 17:41:17 +000084 {
Derek Allard39b622d2008-01-16 21:10:09 +000085 $this->$key = $val;
Derek Allardd2df9bc2007-04-15 17:41:17 +000086 }
87 }
88 elseif (strpos($params, '://'))
89 {
90 if (FALSE === ($dsn = @parse_url($params)))
91 {
92 log_message('error', 'Invalid DB Connection String');
93
94 if ($this->db_debug)
95 {
96 return $this->display_error('db_invalid_connection_str');
97 }
98 return FALSE;
99 }
100
101 $this->hostname = ( ! isset($dsn['host'])) ? '' : rawurldecode($dsn['host']);
102 $this->username = ( ! isset($dsn['user'])) ? '' : rawurldecode($dsn['user']);
103 $this->password = ( ! isset($dsn['pass'])) ? '' : rawurldecode($dsn['pass']);
104 $this->database = ( ! isset($dsn['path'])) ? '' : rawurldecode(substr($dsn['path'], 1));
105 }
Derek Allard39b622d2008-01-16 21:10:09 +0000106
107 log_message('debug', 'Database Driver Class Initialized');
108 }
109
110 // --------------------------------------------------------------------
111
112 /**
113 * Initialize Database Settings
114 *
115 * @access private Called by the constructor
116 * @param mixed
117 * @return void
118 */
119 function initialize($create_db = FALSE)
120 {
Derek Allardd2df9bc2007-04-15 17:41:17 +0000121 // If an existing DB connection resource is supplied
122 // there is no need to connect and select the database
123 if (is_resource($this->conn_id))
124 {
125 return TRUE;
126 }
127
128 // Connect to the database
129 $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
130
131 // No connection? Throw an error
132 if ( ! $this->conn_id)
133 {
134 log_message('error', 'Unable to connect to the database');
135
136 if ($this->db_debug)
137 {
138 $this->display_error('db_unable_to_connect');
139 }
140 return FALSE;
141 }
142
143 // Select the database
144 if ($this->database != '')
145 {
146 if ( ! $this->db_select())
147 {
Derek Allard39b622d2008-01-16 21:10:09 +0000148 // Should we attempt to create the database?
149 if ($create_db == TRUE)
150 {
151 // Load the DB utility class
152 $CI =& get_instance();
153 $CI->load->dbutil();
154
155 // Create the DB
156 if ( ! $CI->dbutil->create_database($this->database))
157 {
158 log_message('error', 'Unable to create database: '.$this->database);
159
160 if ($this->db_debug)
161 {
162 $this->display_error('db_unable_to_create', $this->database);
163 }
164 return FALSE;
165 }
166 else
167 {
168 // In the event the DB was created we need to select it
169 if ($this->db_select())
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
Derek Allardd2df9bc2007-04-15 17:41:17 +0000188 log_message('error', 'Unable to select database: '.$this->database);
189
190 if ($this->db_debug)
191 {
192 $this->display_error('db_unable_to_select', $this->database);
193 }
194 return FALSE;
195 }
Derek Allard39b622d2008-01-16 21:10:09 +0000196
197 if (! $this->db_set_charset($this->char_set, $this->dbcollat))
198 {
199 log_message('error', 'Unable to set database connection charset: '.$this->char_set);
200
201 if ($this->db_debug)
202 {
203 $this->display_error('db_unable_to_set_charset', $this->char_set);
204 }
205
206 return FALSE;
207 }
Derek Allardd2df9bc2007-04-15 17:41:17 +0000208 }
209
210 return TRUE;
211 }
212
213 // --------------------------------------------------------------------
214
215 /**
216 * The name of the platform in use (mysql, mssql, etc...)
217 *
218 * @access public
219 * @return string
220 */
221 function platform()
222 {
223 return $this->dbdriver;
224 }
225
226 // --------------------------------------------------------------------
227
228 /**
229 * Database Version Number. Returns a string containing the
230 * version of the database being used
231 *
232 * @access public
233 * @return string
234 */
235 function version()
236 {
237 if (FALSE === ($sql = $this->_version()))
238 {
239 if ($this->db_debug)
240 {
241 return $this->display_error('db_unsupported_function');
242 }
243 return FALSE;
244 }
245
246 if ($this->dbdriver == 'oci8')
247 {
248 return $sql;
249 }
250
251 $query = $this->query($sql);
Derek Allard39b622d2008-01-16 21:10:09 +0000252 return $query->row('ver');
Derek Allardd2df9bc2007-04-15 17:41:17 +0000253 }
254
255 // --------------------------------------------------------------------
256
257 /**
258 * Execute the query
259 *
260 * Accepts an SQL string as input and returns a result object upon
261 * successful execution of a "read" type query. Returns boolean TRUE
262 * upon successful execution of a "write" type query. Returns boolean
263 * FALSE upon failure, and if the $db_debug variable is set to TRUE
264 * will raise an error.
265 *
266 * @access public
267 * @param string An SQL query string
268 * @param array An array of binding data
269 * @return mixed
270 */
271 function query($sql, $binds = FALSE, $return_object = TRUE)
272 {
273 if ($sql == '')
274 {
275 if ($this->db_debug)
276 {
277 log_message('error', 'Invalid query: '.$sql);
278 return $this->display_error('db_invalid_query');
279 }
280 return FALSE;
281 }
Derek Allard39b622d2008-01-16 21:10:09 +0000282
283 // Verify table prefix and replace if necessary
284 if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
285 {
286 $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
287 }
Derek Allardd2df9bc2007-04-15 17:41:17 +0000288
289 // Is query caching enabled? If the query is a "read type"
290 // we will load the caching class and return the previously
291 // cached query if it exists
292 if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
293 {
294 if ($this->_cache_init())
295 {
296 $this->load_rdriver();
297 if (FALSE !== ($cache = $this->CACHE->read($sql)))
298 {
299 return $cache;
300 }
301 }
302 }
303
304 // Compile binds if needed
305 if ($binds !== FALSE)
306 {
307 $sql = $this->compile_binds($sql, $binds);
308 }
309
310 // Save the query for debugging
Rick Ellis40990462007-07-17 21:40:44 +0000311 if ($this->save_queries == TRUE)
312 {
313 $this->queries[] = $sql;
314 }
Derek Allard39b622d2008-01-16 21:10:09 +0000315
Derek Allardd2df9bc2007-04-15 17:41:17 +0000316 // Start the Query Timer
317 $time_start = list($sm, $ss) = explode(' ', microtime());
318
319 // Run the Query
320 if (FALSE === ($this->result_id = $this->simple_query($sql)))
321 {
322 // This will trigger a rollback if transactions are being used
Rick Ellis28239ad2007-06-11 04:26:39 +0000323 $this->_trans_status = FALSE;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000324
325 if ($this->db_debug)
326 {
327 log_message('error', 'Query error: '.$this->_error_message());
328 return $this->display_error(
329 array(
330 'Error Number: '.$this->_error_number(),
331 $this->_error_message(),
332 $sql
333 )
334 );
335 }
336
Derek Allard39b622d2008-01-16 21:10:09 +0000337 return FALSE;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000338 }
339
340 // Stop and aggregate the query time results
341 $time_end = list($em, $es) = explode(' ', microtime());
342 $this->benchmark += ($em + $es) - ($sm + $ss);
343
344 // Increment the query counter
345 $this->query_count++;
346
347 // Was the query a "write" type?
348 // If so we'll simply return true
349 if ($this->is_write_type($sql) === TRUE)
350 {
351 // If caching is enabled we'll auto-cleanup any
352 // existing files related to this particular URI
353 if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
354 {
355 $this->CACHE->delete();
356 }
357
358 return TRUE;
359 }
360
361 // Return TRUE if we don't need to create a result object
362 // Currently only the Oracle driver uses this when stored
363 // procedures are used
364 if ($return_object !== TRUE)
365 {
366 return TRUE;
367 }
368
369 // Load and instantiate the result driver
370
371 $driver = $this->load_rdriver();
372 $RES = new $driver();
373 $RES->conn_id = $this->conn_id;
374 $RES->result_id = $this->result_id;
Derek Allard39b622d2008-01-16 21:10:09 +0000375 $RES->num_rows = $RES->num_rows();
Derek Allard060052d2007-07-14 14:26:13 +0000376
Derek Allardd2df9bc2007-04-15 17:41:17 +0000377 if ($this->dbdriver == 'oci8')
378 {
379 $RES->stmt_id = $this->stmt_id;
380 $RES->curs_id = NULL;
381 $RES->limit_used = $this->limit_used;
382 }
Derek Allard39b622d2008-01-16 21:10:09 +0000383
Derek Allardd2df9bc2007-04-15 17:41:17 +0000384 // Is query caching enabled? If so, we'll serialize the
385 // result object and save it to a cache file.
386 if ($this->cache_on == TRUE AND $this->_cache_init())
387 {
388 // We'll create a new instance of the result object
389 // only without the platform specific driver since
390 // we can't use it with cached data (the query result
391 // resource ID won't be any good once we've cached the
392 // result object, so we'll have to compile the data
393 // and save it)
394 $CR = new CI_DB_result();
395 $CR->num_rows = $RES->num_rows();
396 $CR->result_object = $RES->result_object();
397 $CR->result_array = $RES->result_array();
398
399 // Reset these since cached objects can not utilize resource IDs.
400 $CR->conn_id = NULL;
401 $CR->result_id = NULL;
402
403 $this->CACHE->write($sql, $CR);
404 }
405
406 return $RES;
407 }
408
409 // --------------------------------------------------------------------
410
411 /**
412 * Load the result drivers
413 *
414 * @access public
415 * @return string the name of the result class
416 */
417 function load_rdriver()
418 {
419 $driver = 'CI_DB_'.$this->dbdriver.'_result';
420
421 if ( ! class_exists($driver))
422 {
423 include_once(BASEPATH.'database/DB_result'.EXT);
424 include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result'.EXT);
425 }
426
427 return $driver;
428 }
429
430 // --------------------------------------------------------------------
431
432 /**
433 * Simple Query
434 * This is a simplified version of the query() function. Internally
435 * we only use it when running transaction commands since they do
436 * not require all the features of the main query() function.
437 *
438 * @access public
439 * @param string the sql query
440 * @return mixed
441 */
442 function simple_query($sql)
443 {
444 if ( ! $this->conn_id)
445 {
446 $this->initialize();
447 }
448
449 return $this->_execute($sql);
450 }
451
452 // --------------------------------------------------------------------
453
454 /**
455 * Disable Transactions
456 * This permits transactions to be disabled at run-time.
457 *
458 * @access public
459 * @return void
460 */
461 function trans_off()
462 {
463 $this->trans_enabled = FALSE;
464 }
465
466 // --------------------------------------------------------------------
467
468 /**
469 * Start Transaction
470 *
471 * @access public
472 * @return void
473 */
474 function trans_start($test_mode = FALSE)
475 {
476 if ( ! $this->trans_enabled)
477 {
478 return FALSE;
479 }
480
481 // When transactions are nested we only begin/commit/rollback the outermost ones
482 if ($this->_trans_depth > 0)
483 {
484 $this->_trans_depth += 1;
485 return;
486 }
487
488 $this->trans_begin($test_mode);
489 }
490
491 // --------------------------------------------------------------------
492
493 /**
494 * Complete Transaction
495 *
496 * @access public
497 * @return bool
498 */
499 function trans_complete()
500 {
501 if ( ! $this->trans_enabled)
502 {
503 return FALSE;
504 }
505
506 // When transactions are nested we only begin/commit/rollback the outermost ones
507 if ($this->_trans_depth > 1)
508 {
509 $this->_trans_depth -= 1;
510 return TRUE;
511 }
512
513 // The query() function will set this flag to TRUE in the event that a query failed
Rick Ellis28239ad2007-06-11 04:26:39 +0000514 if ($this->_trans_status === FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000515 {
516 $this->trans_rollback();
517
518 if ($this->db_debug)
519 {
520 return $this->display_error('db_transaction_failure');
521 }
522 return FALSE;
523 }
524
525 $this->trans_commit();
526 return TRUE;
527 }
528
529 // --------------------------------------------------------------------
530
531 /**
532 * Lets you retrieve the transaction flag to determine if it has failed
533 *
534 * @access public
535 * @return bool
536 */
537 function trans_status()
538 {
Rick Ellis28239ad2007-06-11 04:26:39 +0000539 return $this->_trans_status;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000540 }
541
542 // --------------------------------------------------------------------
543
544 /**
545 * Compile Bindings
546 *
547 * @access public
548 * @param string the sql statement
549 * @param array an array of bind data
550 * @return string
551 */
552 function compile_binds($sql, $binds)
553 {
554 if (FALSE === strpos($sql, $this->bind_marker))
555 {
556 return $sql;
557 }
558
559 if ( ! is_array($binds))
560 {
561 $binds = array($binds);
562 }
563
564 foreach ($binds as $val)
565 {
566 $val = $this->escape($val);
567
568 // Just in case the replacement string contains the bind
569 // character we'll temporarily replace it with a marker
570 $val = str_replace($this->bind_marker, '{%bind_marker%}', $val);
571 $sql = preg_replace("#".preg_quote($this->bind_marker, '#')."#", str_replace('$', '\$', $val), $sql, 1);
572 }
573
574 return str_replace('{%bind_marker%}', $this->bind_marker, $sql);
575 }
576
577 // --------------------------------------------------------------------
578
579 /**
580 * Determines if a query is a "write" type.
581 *
582 * @access public
583 * @param string An SQL query string
584 * @return boolean
585 */
586 function is_write_type($sql)
587 {
588 if ( ! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
589 {
590 return FALSE;
591 }
592 return TRUE;
593 }
594
595 // --------------------------------------------------------------------
596
597 /**
598 * Calculate the aggregate query elapsed time
599 *
600 * @access public
601 * @param integer The number of decimal places
602 * @return integer
603 */
604 function elapsed_time($decimals = 6)
605 {
606 return number_format($this->benchmark, $decimals);
607 }
608
609 // --------------------------------------------------------------------
610
611 /**
612 * Returns the total number of queries
613 *
614 * @access public
615 * @return integer
616 */
617 function total_queries()
618 {
619 return $this->query_count;
620 }
621
622 // --------------------------------------------------------------------
623
624 /**
625 * Returns the last query that was executed
626 *
627 * @access public
628 * @return void
629 */
630 function last_query()
631 {
632 return end($this->queries);
633 }
634
635 // --------------------------------------------------------------------
636
637 /**
Derek Allard39b622d2008-01-16 21:10:09 +0000638 * Protect Identifiers
639 *
640 * This function adds backticks if appropriate based on db type
641 *
642 * @access private
643 * @param mixed the item to escape
644 * @param boolean only affect the first word
645 * @return mixed the item with backticks
646 */
647 function protect_identifiers($item, $first_word_only = FALSE)
648 {
649 return $this->_protect_identifiers($item, $first_word_only = FALSE);
650 }
651
652 // --------------------------------------------------------------------
653
654 /**
Derek Allardd2df9bc2007-04-15 17:41:17 +0000655 * "Smart" Escape String
656 *
657 * Escapes data based on type
658 * Sets boolean and null types
659 *
660 * @access public
661 * @param string
662 * @return integer
663 */
664 function escape($str)
665 {
666 switch (gettype($str))
667 {
668 case 'string' : $str = "'".$this->escape_str($str)."'";
669 break;
670 case 'boolean' : $str = ($str === FALSE) ? 0 : 1;
671 break;
672 default : $str = ($str === NULL) ? 'NULL' : $str;
673 break;
674 }
675
676 return $str;
677 }
678
679 // --------------------------------------------------------------------
680
681 /**
682 * Primary
683 *
684 * Retrieves the primary key. It assumes that the row in the first
685 * position is the primary key
686 *
687 * @access public
688 * @param string the table name
689 * @return string
690 */
691 function primary($table = '')
692 {
693 $fields = $this->list_fields($table);
694
695 if ( ! is_array($fields))
696 {
697 return FALSE;
698 }
699
700 return current($fields);
701 }
702
703 // --------------------------------------------------------------------
704
705 /**
706 * Returns an array of table names
707 *
708 * @access public
709 * @return array
710 */
Derek Allard39b622d2008-01-16 21:10:09 +0000711 function list_tables($constrain_by_prefix = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000712 {
713 // Is there a cached result?
714 if (isset($this->data_cache['table_names']))
715 {
716 return $this->data_cache['table_names'];
717 }
718
Derek Allard39b622d2008-01-16 21:10:09 +0000719 if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
Derek Allardd2df9bc2007-04-15 17:41:17 +0000720 {
721 if ($this->db_debug)
722 {
723 return $this->display_error('db_unsupported_function');
724 }
725 return FALSE;
726 }
727
728 $retval = array();
729 $query = $this->query($sql);
730
731 if ($query->num_rows() > 0)
732 {
733 foreach($query->result_array() as $row)
734 {
735 if (isset($row['TABLE_NAME']))
736 {
737 $retval[] = $row['TABLE_NAME'];
738 }
739 else
740 {
741 $retval[] = array_shift($row);
742 }
743 }
744 }
745
746 $this->data_cache['table_names'] = $retval;
747 return $this->data_cache['table_names'];
748 }
749
750 // --------------------------------------------------------------------
751
752 /**
753 * Determine if a particular table exists
754 * @access public
755 * @return boolean
756 */
757 function table_exists($table_name)
758 {
Derek Allard39b622d2008-01-16 21:10:09 +0000759 return ( ! in_array($this->prep_tablename($table_name), $this->list_tables())) ? FALSE : TRUE;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000760 }
761
762 // --------------------------------------------------------------------
763
764 /**
765 * Fetch MySQL Field Names
766 *
767 * @access public
768 * @param string the table name
769 * @return array
770 */
771 function list_fields($table = '')
772 {
773 // Is there a cached result?
774 if (isset($this->data_cache['field_names'][$table]))
775 {
776 return $this->data_cache['field_names'][$table];
777 }
778
779 if ($table == '')
780 {
781 if ($this->db_debug)
782 {
783 return $this->display_error('db_field_param_missing');
784 }
785 return FALSE;
786 }
787
Derek Allard39b622d2008-01-16 21:10:09 +0000788 if (FALSE === ($sql = $this->_list_columns($this->prep_tablename($table))))
Derek Allardd2df9bc2007-04-15 17:41:17 +0000789 {
790 if ($this->db_debug)
791 {
792 return $this->display_error('db_unsupported_function');
793 }
794 return FALSE;
795 }
796
797 $query = $this->query($sql);
798
799 $retval = array();
800 foreach($query->result_array() as $row)
801 {
802 if (isset($row['COLUMN_NAME']))
803 {
804 $retval[] = $row['COLUMN_NAME'];
805 }
806 else
807 {
808 $retval[] = current($row);
809 }
810 }
811
812 $this->data_cache['field_names'][$table] = $retval;
813 return $this->data_cache['field_names'][$table];
814 }
815
816 // --------------------------------------------------------------------
817
818 /**
819 * Determine if a particular field exists
820 * @access public
821 * @param string
822 * @param string
823 * @return boolean
824 */
825 function field_exists($field_name, $table_name)
826 {
827 return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
828 }
829
830 // --------------------------------------------------------------------
831
832 /**
833 * DEPRECATED - use list_fields()
834 */
835 function field_names($table = '')
836 {
837 return $this->list_fields($table);
838 }
839
840 // --------------------------------------------------------------------
841
842 /**
843 * Returns an object with field data
844 *
845 * @access public
846 * @param string the table name
847 * @return object
848 */
849 function field_data($table = '')
850 {
851 if ($table == '')
852 {
853 if ($this->db_debug)
854 {
855 return $this->display_error('db_field_param_missing');
856 }
857 return FALSE;
858 }
859
Derek Allard39b622d2008-01-16 21:10:09 +0000860 $query = $this->query($this->_field_data($this->prep_tablename($table)));
Derek Allardd2df9bc2007-04-15 17:41:17 +0000861 return $query->field_data();
862 }
863
864 // --------------------------------------------------------------------
865
866 /**
867 * Generate an insert string
868 *
869 * @access public
870 * @param string the table upon which the query will be performed
871 * @param array an associative array data of key/values
872 * @return string
873 */
874 function insert_string($table, $data)
875 {
876 $fields = array();
877 $values = array();
878
879 foreach($data as $key => $val)
880 {
881 $fields[] = $key;
882 $values[] = $this->escape($val);
883 }
Derek Allard39b622d2008-01-16 21:10:09 +0000884
885
886 return $this->_insert($this->prep_tablename($table), $fields, $values);
887 }
Derek Allardd2df9bc2007-04-15 17:41:17 +0000888
889 // --------------------------------------------------------------------
890
891 /**
892 * Generate an update string
893 *
894 * @access public
895 * @param string the table upon which the query will be performed
896 * @param array an associative array data of key/values
897 * @param mixed the "where" statement
898 * @return string
899 */
900 function update_string($table, $data, $where)
901 {
902 if ($where == '')
903 return false;
904
905 $fields = array();
906 foreach($data as $key => $val)
907 {
908 $fields[$key] = $this->escape($val);
909 }
910
911 if ( ! is_array($where))
912 {
913 $dest = array($where);
914 }
915 else
916 {
917 $dest = array();
918 foreach ($where as $key => $val)
919 {
920 $prefix = (count($dest) == 0) ? '' : ' AND ';
921
Derek Allard39b622d2008-01-16 21:10:09 +0000922 if ($val !== '')
Derek Allardd2df9bc2007-04-15 17:41:17 +0000923 {
924 if ( ! $this->_has_operator($key))
925 {
926 $key .= ' =';
927 }
928
929 $val = ' '.$this->escape($val);
930 }
931
932 $dest[] = $prefix.$key.$val;
933 }
934 }
935
Derek Allard39b622d2008-01-16 21:10:09 +0000936 return $this->_update($this->prep_tablename($table), $fields, $dest);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000937 }
938
939 // --------------------------------------------------------------------
940
941 /**
Derek Allard39b622d2008-01-16 21:10:09 +0000942 * Prep the table name - simply adds the table prefix if needed
943 *
944 * @access public
945 * @param string the table name
946 * @return string
947 */
948 function prep_tablename($table = '')
949 {
950 // Do we need to add the table prefix?
951 if ($this->dbprefix != '')
952 {
953 if (substr($table, 0, strlen($this->dbprefix)) != $this->dbprefix)
954 {
955 $table = $this->dbprefix.$table;
956 }
957 }
958
959 return $table;
960 }
961
962 // --------------------------------------------------------------------
963
964 /**
Derek Allardd2df9bc2007-04-15 17:41:17 +0000965 * Enables a native PHP function to be run, using a platform agnostic wrapper.
966 *
967 * @access public
968 * @param string the function name
969 * @param mixed any parameters needed by the function
970 * @return mixed
971 */
972 function call_function($function)
973 {
974 $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
975
976 if (FALSE === strpos($driver, $function))
977 {
978 $function = $driver.$function;
979 }
980
981 if ( ! function_exists($function))
982 {
983 if ($this->db_debug)
984 {
985 return $this->display_error('db_unsupported_function');
986 }
987 return FALSE;
988 }
989 else
990 {
991 $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
992
993 return call_user_func_array($function, $args);
994 }
995 }
996
997 // --------------------------------------------------------------------
998
999 /**
1000 * Set Cache Directory Path
1001 *
1002 * @access public
1003 * @param string the path to the cache directory
1004 * @return void
1005 */
1006 function cache_set_path($path = '')
1007 {
1008 $this->cachedir = $path;
1009 }
1010
1011 // --------------------------------------------------------------------
1012
1013 /**
1014 * Enable Query Caching
1015 *
1016 * @access public
1017 * @return void
1018 */
1019 function cache_on()
1020 {
1021 $this->cache_on = TRUE;
1022 return TRUE;
1023 }
1024
1025 // --------------------------------------------------------------------
1026
1027 /**
1028 * Disable Query Caching
1029 *
1030 * @access public
1031 * @return void
1032 */
1033 function cache_off()
1034 {
1035 $this->cache_on = FALSE;
1036 return FALSE;
1037 }
1038
1039
1040 // --------------------------------------------------------------------
1041
1042 /**
1043 * Delete the cache files associated with a particular URI
1044 *
1045 * @access public
1046 * @return void
1047 */
1048 function cache_delete($segment_one = '', $segment_two = '')
1049 {
1050 if ( ! $this->_cache_init())
1051 {
1052 return FALSE;
1053 }
1054 return $this->CACHE->delete($segment_one, $segment_two);
1055 }
1056
1057 // --------------------------------------------------------------------
1058
1059 /**
1060 * Delete All cache files
1061 *
1062 * @access public
1063 * @return void
1064 */
1065 function cache_delete_all()
1066 {
1067 if ( ! $this->_cache_init())
1068 {
1069 return FALSE;
1070 }
1071
1072 return $this->CACHE->delete_all();
1073 }
1074
1075 // --------------------------------------------------------------------
1076
1077 /**
1078 * Initialize the Cache Class
1079 *
1080 * @access private
1081 * @return void
1082 */
1083 function _cache_init()
1084 {
1085 if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
1086 {
1087 return TRUE;
1088 }
1089
1090 if ( ! @include(BASEPATH.'database/DB_cache'.EXT))
1091 {
1092 return $this->cache_off();
1093 }
1094
1095 $this->CACHE = new CI_DB_Cache;
1096 return TRUE;
1097 }
1098
Derek Allardd2df9bc2007-04-15 17:41:17 +00001099 // --------------------------------------------------------------------
1100
1101 /**
1102 * Close DB Connection
1103 *
1104 * @access public
1105 * @return void
1106 */
1107 function close()
1108 {
1109 if (is_resource($this->conn_id))
1110 {
1111 $this->_close($this->conn_id);
1112 }
1113 $this->conn_id = FALSE;
1114 }
1115
1116 // --------------------------------------------------------------------
1117
1118 /**
1119 * Display an error message
1120 *
1121 * @access public
1122 * @param string the error message
1123 * @param string any "swap" values
1124 * @param boolean whether to localize the message
1125 * @return string sends the application/error_db.php template
1126 */
1127 function display_error($error = '', $swap = '', $native = FALSE)
1128 {
Derek Allard39b622d2008-01-16 21:10:09 +00001129// $LANG = new CI_Lang();
Derek Allardd2df9bc2007-04-15 17:41:17 +00001130 $LANG = new CI_Language();
1131 $LANG->load('db');
1132
1133 $heading = 'MySQL Error';
1134
1135 if ($native == TRUE)
1136 {
1137 $message = $error;
1138 }
1139 else
1140 {
1141 $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
1142 }
1143
1144 if ( ! class_exists('CI_Exceptions'))
1145 {
Derek Allard39b622d2008-01-16 21:10:09 +00001146// include(BASEPATH.'core/Exceptions'.EXT);
Derek Allardd2df9bc2007-04-15 17:41:17 +00001147 include(BASEPATH.'libraries/Exceptions'.EXT);
1148 }
1149
1150 $error = new CI_Exceptions();
1151 echo $error->show_error('An Error Was Encountered', $message, 'error_db');
1152 exit;
1153 }
1154
1155}
1156
admin7b613c72006-09-24 18:05:17 +00001157?>