blob: 5102cc74c0b550428c77043a6b3d11cd080b2c24 [file] [log] [blame]
admin7b613c72006-09-24 18:05:17 +00001<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * Code Igniter
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, pMachine, Inc.
10 * @license http://www.codeignitor.com/user_guide/license.html
11 * @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 = '';
39 var $port = '';
40 var $pconnect = FALSE;
41 var $conn_id = FALSE;
42 var $result_id = FALSE;
43 var $db_debug = FALSE;
44 var $benchmark = 0;
45 var $query_count = 0;
46 var $bind_marker = '?';
47 var $queries = array();
admin3ed8c512006-09-29 23:26:28 +000048 var $cache = array();
admin7b613c72006-09-24 18:05:17 +000049 var $trans_enabled = TRUE;
50 var $_trans_depth = 0;
51 var $_trans_failure = FALSE; // Used with transactions to determine if a rollback should occur
52
53 // These are use with Oracle
54 var $stmt_id;
55 var $curs_id;
56 var $limit_used;
57
58
59 /**
60 * Constructor. Accepts one parameter containing the database
61 * connection settings.
62 *
63 * Database settings can be passed as discreet
64 * parameters or as a data source name in the first
65 * parameter. DSNs must have this prototype:
66 * $dsn = 'driver://username:password@hostname/database';
67 *
68 * @param mixed. Can be an array or a DSN string
69 */
70 function CI_DB_driver($params)
71 {
72 $this->initialize($params);
73 log_message('debug', 'Database Driver Class Initialized');
74 }
75
76 // --------------------------------------------------------------------
77
78 /**
79 * Initialize Database Settings
80 *
81 * @access private Called by the constructor
82 * @param mixed
83 * @return void
84 */
85 function initialize($params = '')
86 {
87 if (is_array($params))
88 {
89 foreach (array('hostname' => '', 'username' => '', 'password' => '', 'database' => '', 'dbdriver' => 'mysql', 'dbprefix' => '', 'port' => '', 'pconnect' => FALSE, 'db_debug' => FALSE) as $key => $val)
90 {
91 $this->$key = ( ! isset($params[$key])) ? $val : $params[$key];
92 }
93 }
94 elseif (strpos($params, '://'))
95 {
96 if (FALSE === ($dsn = @parse_url($params)))
97 {
98 log_message('error', 'Invalid DB Connection String');
99
100 if ($this->db_debug)
101 {
102 return $this->display_error('db_invalid_connection_str');
103 }
104 return FALSE;
105 }
106
107 $this->hostname = ( ! isset($dsn['host'])) ? '' : rawurldecode($dsn['host']);
108 $this->username = ( ! isset($dsn['user'])) ? '' : rawurldecode($dsn['user']);
109 $this->password = ( ! isset($dsn['pass'])) ? '' : rawurldecode($dsn['pass']);
110 $this->database = ( ! isset($dsn['path'])) ? '' : rawurldecode(substr($dsn['path'], 1));
111 }
112
113 if ($this->pconnect == FALSE)
114 {
115 $this->conn_id = $this->db_connect();
116 }
117 else
118 {
119 $this->conn_id = $this->db_pconnect();
120 }
121
122 if ( ! $this->conn_id)
123 {
124 log_message('error', 'Unable to connect to the database');
125
126 if ($this->db_debug)
127 {
128 $this->display_error('db_unable_to_connect');
129 }
130 }
131 else
132 {
133 if ( ! $this->db_select())
134 {
135 log_message('error', 'Unable to select database: '.$this->database);
136
137 if ($this->db_debug)
138 {
139 $this->display_error('db_unable_to_select', $this->database);
140 }
141 }
142 }
143 }
144
145
146 // --------------------------------------------------------------------
147
148 /**
admin9cd4e8e2006-09-25 23:26:25 +0000149 * The name of the platform in use (mysql, mssql, etc...)
150 *
151 * @access public
152 * @return string
153 */
154 function platform()
155 {
156 return $this->dbdriver;
157 }
158
159 // --------------------------------------------------------------------
160
161 /**
162 * Database Version Number. Returns a string containing the
163 * version of the database being used
164 *
165 * @access public
166 * @return string
167 */
168 function version()
169 {
170 if (FALSE === ($sql = $this->_version()))
171 {
172 if ($this->db_debug)
173 {
174 return $this->display_error('db_unsupported_function');
175 }
176 return FALSE;
177 }
178
179 if ($this->dbdriver == 'oci8')
180 {
181 return $sql;
182 }
183
184 $query = $this->query($sql);
185 $row = $query->row();
186 return $row->ver;
187 }
188
189 // --------------------------------------------------------------------
190
191 /**
admin7b613c72006-09-24 18:05:17 +0000192 * Execute the query
193 *
194 * Accepts an SQL string as input and returns a result object upon
195 * successful execution of a "read" type query. Returns boolean TRUE
196 * upon successful execution of a "write" type query. Returns boolean
197 * FALSE upon failure, and if the $db_debug variable is set to TRUE
198 * will raise an error.
199 *
200 * @access public
201 * @param string An SQL query string
202 * @param array An array of binding data
203 * @return mixed
204 */
205 function query($sql, $binds = FALSE, $return_object = TRUE)
206 {
207 if ($sql == '')
208 {
209 if ($this->db_debug)
210 {
211 log_message('error', 'Invalid query: '.$sql);
212 return $this->display_error('db_invalid_query');
213 }
214 return FALSE;
215 }
216
217 // Compile binds if needed
218 if ($binds !== FALSE)
219 {
220 $sql = $this->compile_binds($sql, $binds);
221 }
222
223 // Save the query for debugging
224 $this->queries[] = $sql;
225
226 // Start the Query Timer
227 $time_start = list($sm, $ss) = explode(' ', microtime());
228
229 // Run the Query
230 if (FALSE === ($this->result_id = $this->simple_query($sql)))
231 {
232 // This will trigger a rollback if transactions are being used
233 $this->_trans_failure = TRUE;
234
235 if ($this->db_debug)
236 {
adminbb1d4392006-09-24 20:14:38 +0000237 log_message('error', 'Query error: '.$this->_error_message());
admin7b613c72006-09-24 18:05:17 +0000238 return $this->display_error(
239 array(
adminbb1d4392006-09-24 20:14:38 +0000240 'Error Number: '.$this->_error_number(),
241 $this->_error_message(),
admin7b613c72006-09-24 18:05:17 +0000242 $sql
243 )
244 );
245 }
246
247 return FALSE;
248 }
249
250 // Stop and aggregate the query time results
251 $time_end = list($em, $es) = explode(' ', microtime());
252 $this->benchmark += ($em + $es) - ($sm + $ss);
253
254 // Increment the query counter
255 $this->query_count++;
256
257 // Was the query a "write" type?
258 // If so we'll simply return true
259 if ($this->is_write_type($sql) === TRUE)
260 {
261 return TRUE;
262 }
263
264 // Return TRUE if we don't need to create a result object
265 // Currently only the Oracle driver uses this when stored
266 // procedures are used
267 if ($return_object !== TRUE)
268 {
269 return TRUE;
270 }
271
272 // Define the result driver name
273 $result = 'CI_DB_'.$this->dbdriver.'_result';
274
275 // Load the result classes
276 if ( ! class_exists($result))
277 {
278 include_once(BASEPATH.'database/DB_result'.EXT);
279 include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result'.EXT);
280 }
281
282 // Instantiate the result object
283 $RES = new $result();
284 $RES->conn_id = $this->conn_id;
285 $RES->db_debug = $this->db_debug;
286 $RES->result_id = $this->result_id;
287
288 if ($this->dbdriver == 'oci8')
289 {
290 $RES->stmt_id = $this->stmt_id;
291 $RES->curs_id = NULL;
292 $RES->limit_used = $this->limit_used;
293 }
294
295 return $RES;
296 }
297
298 // --------------------------------------------------------------------
299
300 /**
301 * Simple Query
302 * This is a simiplified version of the query() function. Internally
303 * we only use it when running transaction commands since they do
304 * not require all the features of the main query() function.
305 *
306 * @access public
307 * @param string the sql query
308 * @return mixed
309 */
310 function simple_query($sql)
311 {
312 if ( ! $this->conn_id)
313 {
314 $this->initialize();
315 }
316
317 return $this->_execute($sql, $this->conn_id);
318 }
319
320 // --------------------------------------------------------------------
321
322 /**
323 * Disable Transactions
324 * This permits transactions to be disabled at run-time.
325 *
326 * @access public
327 * @return void
328 */
329 function trans_off()
330 {
331 $this->trans_enabled = FALSE;
332 }
333
334 // --------------------------------------------------------------------
335
336 /**
337 * Start Transaction
338 *
339 * @access public
340 * @return void
341 */
342 function trans_start($test_mode = FALSE)
343 {
344 if ( ! $this->trans_enabled)
345 {
346 return FALSE;
347 }
348
349 // When transactions are nested we only begin/commit/rollback the outermost ones
350 if ($this->_trans_depth > 0)
351 {
352 $this->_trans_depth += 1;
353 return;
354 }
355
356 $this->trans_begin($test_mode);
357 }
358
359 // --------------------------------------------------------------------
360
361 /**
362 * Complete Transaction
363 *
364 * @access public
365 * @return bool
366 */
367 function trans_complete()
368 {
369 if ( ! $this->trans_enabled)
370 {
371 return FALSE;
372 }
373
374 // When transactions are nested we only begin/commit/rollback the outermost ones
375 if ($this->_trans_depth > 1)
376 {
377 $this->_trans_depth -= 1;
378 return TRUE;
379 }
380
381 // The query() function will set this flag to TRUE in the event that a query failed
382 if ($this->_trans_failure === TRUE)
383 {
384 $this->trans_rollback();
385
386 if ($this->db_debug)
387 {
388 return $this->display_error('db_transaction_failure');
389 }
390 return FALSE;
391 }
392
393 $this->trans_commit();
394 return TRUE;
395 }
396
397 // --------------------------------------------------------------------
398
399 /**
400 * Lets you retrieve the transaction flag to determine if it has failed
401 *
402 * @access public
403 * @return bool
404 */
405 function trans_status()
406 {
407 return $this->_trans_failure;
408 }
409
410 // --------------------------------------------------------------------
411
412 /**
413 * Compile Bindings
414 *
415 * @access public
416 * @param string the sql statement
417 * @param array an array of bind data
418 * @return string
419 */
420 function compile_binds($sql, $binds)
421 {
422 if (FALSE === strpos($sql, $this->bind_marker))
423 {
424 return $sql;
425 }
426
427 if ( ! is_array($binds))
428 {
429 $binds = array($binds);
430 }
431
432 foreach ($binds as $val)
433 {
434 $val = $this->escape($val);
435
436 // Just in case the replacement string contains the bind
437 // character we'll temporarily replace it with a marker
438 $val = str_replace($this->bind_marker, '{%bind_marker%}', $val);
439 $sql = preg_replace("#".preg_quote($this->bind_marker, '#')."#", str_replace('$', '\$', $val), $sql, 1);
440 }
441
442 return str_replace('{%bind_marker%}', $this->bind_marker, $sql);
443 }
444
445 // --------------------------------------------------------------------
446
447 /**
448 * Determines if a query is a "write" type.
449 *
450 * @access public
451 * @param string An SQL query string
452 * @return boolean
453 */
454 function is_write_type($sql)
455 {
456 if ( ! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
457 {
458 return FALSE;
459 }
460 return TRUE;
461 }
462
463 // --------------------------------------------------------------------
464
465 /**
466 * Calculate the aggregate query elapsed time
467 *
468 * @access public
469 * @param intiger The number of decimal places
470 * @return integer
471 */
472 function elapsed_time($decimals = 6)
473 {
474 return number_format($this->benchmark, $decimals);
475 }
476
477 // --------------------------------------------------------------------
478
479 /**
480 * Returns the total number of queries
481 *
482 * @access public
483 * @return integer
484 */
485 function total_queries()
486 {
487 return $this->query_count;
488 }
489
490 // --------------------------------------------------------------------
491
492 /**
493 * Returns the last query that was executed
494 *
495 * @access public
496 * @return void
497 */
498 function last_query()
499 {
500 return end($this->queries);
501 }
502
503 // --------------------------------------------------------------------
504
505 /**
506 * "Smart" Escape String
507 *
508 * Escapes data based on type
509 * Sets boolean and null types
510 *
511 * @access public
512 * @param string
513 * @return integer
514 */
515 function escape($str)
516 {
517 switch (gettype($str))
518 {
519 case 'string' : $str = "'".$this->escape_str($str)."'";
520 break;
521 case 'boolean' : $str = ($str === FALSE) ? 0 : 1;
522 break;
523 default : $str = ($str === NULL) ? 'NULL' : $str;
524 break;
525 }
526
527 return $str;
adminbb1d4392006-09-24 20:14:38 +0000528 }
529
admin9cd4e8e2006-09-25 23:26:25 +0000530
531
532 // --------------------------------------------------------------------
533
534 /**
535 * Primary
536 *
537 * Retrieves the primary key. It assumes that the row in the first
538 * position is the primary key
539 *
540 * @access public
541 * @param string the table name
542 * @return string
543 */
544 function primary($table = '')
545 {
546 $fields = $this->field_names($table);
547
548 if ( ! is_array($fields))
549 {
550 return FALSE;
551 }
552
553 return current($fields);
554 }
555
556 // --------------------------------------------------------------------
557
admin3dd978f2006-09-30 19:24:45 +0000558 // --------------------------------------------------------------------
559
560 /**
561 * List databases
562 *
563 * @access public
564 * @return bool
565 */
566 function list_databases()
567 {
568 // Is there a cached result?
569 if (isset($this->cache['db_names']))
570 {
571 return $this->cache['db_names'];
572 }
573
574 $query = $this->query($this->_list_database());
575 $dbs = array();
576 if ($query->num_rows() > 0)
577 {
578 foreach ($query->result_array() as $row)
579 {
580 $dbs[] = current($row);
581 }
582 }
583
584 return $this->cache['db_names'] =& $dbs;
585 }
586
587 // --------------------------------------------------------------------
588
589 /**
590 * Returns an array of table names
591 *
592 * @access public
593 * @return array
594 */
595 function list_tables()
596 {
597 // Is there a cached result?
598 if (isset($this->cache['table_names']))
599 {
600 return $this->cache['table_names'];
601 }
602
603 if (FALSE === ($sql = $this->_list_tables()))
604 {
605 if ($this->db_debug)
606 {
607 return $this->display_error('db_unsupported_function');
608 }
609 return FALSE;
610 }
611
612 $retval = array();
613 $query = $this->query($sql);
614
615 if ($query->num_rows() > 0)
616 {
617 foreach($query->result_array() as $row)
618 {
619 if (isset($row['TABLE_NAME']))
620 {
621 $retval[] = $row['TABLE_NAME'];
622 }
623 else
624 {
625 $retval[] = array_shift($row);
626 }
627 }
628 }
629
630 return $this->cache['table_names'] =& $retval;
631 }
632
633 // --------------------------------------------------------------------
634
635 /**
636 * Determine if a particular table exists
637 * @access public
638 * @return boolean
639 */
640 function table_exists($table_name)
641 {
642 return ( ! in_array($this->dbprefix.$table_name, $this->list_tables())) ? FALSE : TRUE;
643 }
644
645 // --------------------------------------------------------------------
646
admin9cd4e8e2006-09-25 23:26:25 +0000647 /**
648 * Fetch MySQL Field Names
649 *
650 * @access public
651 * @param string the table name
652 * @return array
653 */
admin3dd978f2006-09-30 19:24:45 +0000654 function list_fields($table = '')
admin9cd4e8e2006-09-25 23:26:25 +0000655 {
admin3ed8c512006-09-29 23:26:28 +0000656 // Is there a cached result?
657 if (isset($this->cache['field_names'][$table]))
658 {
659 return $this->cache['field_names'][$table];
660 }
661
admin9cd4e8e2006-09-25 23:26:25 +0000662 if ($table == '')
663 {
664 if ($this->db_debug)
665 {
666 return $this->display_error('db_field_param_missing');
667 }
668 return FALSE;
669 }
670
671 if (FALSE === ($sql = $this->_list_columns($this->dbprefix.$table)))
672 {
673 if ($this->db_debug)
674 {
675 return $this->display_error('db_unsupported_function');
676 }
677 return FALSE;
678 }
679
680 $query = $this->query($sql);
681
682 $retval = array();
683 foreach($query->result_array() as $row)
684 {
685 if (isset($row['COLUMN_NAME']))
686 {
687 $retval[] = $row['COLUMN_NAME'];
688 }
689 else
690 {
691 $retval[] = current($row);
692 }
693 }
694
admin3ed8c512006-09-29 23:26:28 +0000695 return $this->cache['field_names'][$table] =& $retval;
admin9cd4e8e2006-09-25 23:26:25 +0000696 }
admin3dd978f2006-09-30 19:24:45 +0000697
698 // --------------------------------------------------------------------
699
700 /**
701 * DEPRECATED - use list_fields()
702 */
703 function field_names($table = '')
704 {
705 return $this->list_fields($table);
706 }
admin9cd4e8e2006-09-25 23:26:25 +0000707
708 // --------------------------------------------------------------------
709
710 /**
711 * Returns an object with field data
712 *
713 * @access public
714 * @param string the table name
715 * @return object
716 */
717 function field_data($table = '')
718 {
719 if ($table == '')
720 {
721 if ($this->db_debug)
722 {
723 return $this->display_error('db_field_param_missing');
724 }
725 return FALSE;
726 }
727
728 $query = $this->query($this->_field_data($this->dbprefix.$table));
729 return $query->field_data();
730 }
731
adminbb1d4392006-09-24 20:14:38 +0000732 // --------------------------------------------------------------------
733
734 /**
735 * Generate an insert string
736 *
737 * @access public
738 * @param string the table upon which the query will be performed
739 * @param array an associative array data of key/values
740 * @return string
741 */
742 function insert_string($table, $data)
743 {
744 $fields = array();
745 $values = array();
746
747 foreach($data as $key => $val)
748 {
749 $fields[] = $key;
750 $values[] = $this->escape($val);
751 }
752
753 return $this->_insert($this->dbprefix.$table, $fields, $values);
754 }
755
756 // --------------------------------------------------------------------
757
758 /**
759 * Generate an update string
760 *
761 * @access public
762 * @param string the table upon which the query will be performed
763 * @param array an associative array data of key/values
764 * @param mixed the "where" statement
765 * @return string
766 */
767 function update_string($table, $data, $where)
768 {
769 if ($where == '')
770 return false;
771
772 $fields = array();
773 foreach($data as $key => $val)
774 {
775 $fields[$key] = $this->escape($val);
776 }
777
778 if ( ! is_array($where))
779 {
780 $dest = array($where);
781 }
782 else
783 {
784 $dest = array();
785 foreach ($where as $key => $val)
786 {
787 $prefix = (count($dest) == 0) ? '' : ' AND ';
788
789 if ($val != '')
790 {
791 if ( ! $this->_has_operator($key))
792 {
793 $key .= ' =';
794 }
795
796 $val = ' '.$this->escape($val);
797 }
798
799 $dest[] = $prefix.$key.$val;
800 }
801 }
802
803 return $this->_update($this->dbprefix.$table, $fields, $dest);
804 }
admin7b613c72006-09-24 18:05:17 +0000805
806 // --------------------------------------------------------------------
807
808 /**
809 * Enables a native PHP function to be run, using a platform agnostic wrapper.
810 *
811 * @access public
812 * @param string the function name
813 * @param mixed any parameters needed by the function
814 * @return mixed
815 */
816 function call_function($function)
817 {
818 $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
819
820 if (FALSE === strpos($driver, $function))
821 {
822 $function = $driver.$function;
823 }
824
825 if ( ! function_exists($function))
826 {
827 if ($this->db_debug)
828 {
829 return $this->display_error('db_unsupported_function');
830 }
831 return FALSE;
832 }
833 else
834 {
adminee54c112006-09-28 17:13:38 +0000835 $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
836
admin7b613c72006-09-24 18:05:17 +0000837 return call_user_func_array($function, $args);
838 }
839 }
840
841 // --------------------------------------------------------------------
842
843 /**
844 * Close DB Connection
845 *
846 * @access public
847 * @return void
848 */
849 function close()
850 {
851 if (is_resource($this->conn_id))
852 {
853 $this->_close($this->conn_id);
854 }
855 $this->conn_id = FALSE;
856 }
857
858 // --------------------------------------------------------------------
859
860 /**
861 * Display an error message
862 *
863 * @access public
864 * @param string the error message
865 * @param string any "swap" values
866 * @param boolean whether to localize the message
867 * @return string sends the application/errror_db.php template
868 */
869 function display_error($error = '', $swap = '', $native = FALSE)
870 {
871 $LANG = new CI_Language();
872 $LANG->load('db');
873
874 $heading = 'MySQL Error';
875
876 if ($native == TRUE)
877 {
878 $message = $error;
879 }
880 else
881 {
882 $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
883 }
884
885 if ( ! class_exists('CI_Exceptions'))
886 {
887 include_once(BASEPATH.'libraries/Exceptions'.EXT);
888 }
889
890 $error = new CI_Exceptions();
891 echo $error->show_error('An Error Was Encountered', $message, 'error_db');
892 exit;
893
894 }
895
896}
897
898?>