Subversion-Projekte lars-tiefland.codeigniter

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?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
 */
31
class 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
	{
616
		if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
617
		{
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)
676
	{
677
		switch (gettype($str))
678
		{
679
			case 'string'	:	$str = "'".$this->escape_str($str)."'";
680
				break;
681
			case 'boolean'	:	$str = ($str === FALSE) ? 0 : 1;
682
				break;
683
			default			:	$str = ($str === NULL) ? 'NULL' : $str;
684
				break;
685
		}
686
 
687
		return $str;
688
	}
689
 
690
	// --------------------------------------------------------------------
691
 
692
	/**
693
	 * Primary
694
	 *
695
	 * Retrieves the primary key.  It assumes that the row in the first
696
	 * position is the primary key
697
	 *
698
	 * @access	public
699
	 * @param	string	the table name
700
	 * @return	string
701
	 */
702
	function primary($table = '')
703
	{
704
		$fields = $this->list_fields($table);
705
 
706
		if ( ! is_array($fields))
707
		{
708
			return FALSE;
709
		}
710
 
711
		return current($fields);
712
	}
713
 
714
	// --------------------------------------------------------------------
715
 
716
	/**
717
	 * Returns an array of table names
718
	 *
719
	 * @access	public
720
	 * @return	array
721
	 */
722
	function list_tables($constrain_by_prefix = FALSE)
723
	{
724
		// Is there a cached result?
725
		if (isset($this->data_cache['table_names']))
726
		{
727
			return $this->data_cache['table_names'];
728
		}
729
 
730
		if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
731
		{
732
			if ($this->db_debug)
733
			{
734
				return $this->display_error('db_unsupported_function');
735
			}
736
			return FALSE;
737
		}
738
 
739
		$retval = array();
740
		$query = $this->query($sql);
741
 
742
		if ($query->num_rows() > 0)
743
		{
744
			foreach($query->result_array() as $row)
745
			{
746
				if (isset($row['TABLE_NAME']))
747
				{
748
					$retval[] = $row['TABLE_NAME'];
749
				}
750
				else
751
				{
752
					$retval[] = array_shift($row);
753
				}
754
			}
755
		}
756
 
757
		$this->data_cache['table_names'] = $retval;
758
		return $this->data_cache['table_names'];
759
	}
760
 
761
	// --------------------------------------------------------------------
762
 
763
	/**
764
	 * Determine if a particular table exists
765
	 * @access	public
766
	 * @return	boolean
767
	 */
768
	function table_exists($table_name)
769
	{
770
		return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE;
771
	}
772
 
773
	// --------------------------------------------------------------------
774
 
775
	/**
776
	 * Fetch MySQL Field Names
777
	 *
778
	 * @access	public
779
	 * @param	string	the table name
780
	 * @return	array
781
	 */
782
	function list_fields($table = '')
783
	{
784
		// Is there a cached result?
785
		if (isset($this->data_cache['field_names'][$table]))
786
		{
787
			return $this->data_cache['field_names'][$table];
788
		}
789
 
790
		if ($table == '')
791
		{
792
			if ($this->db_debug)
793
			{
794
				return $this->display_error('db_field_param_missing');
795
			}
796
			return FALSE;
797
		}
798
 
799
		if (FALSE === ($sql = $this->_list_columns($this->_protect_identifiers($table, TRUE, NULL, FALSE))))
800
		{
801
			if ($this->db_debug)
802
			{
803
				return $this->display_error('db_unsupported_function');
804
			}
805
			return FALSE;
806
		}
807
 
808
		$query = $this->query($sql);
809
 
810
		$retval = array();
811
		foreach($query->result_array() as $row)
812
		{
813
			if (isset($row['COLUMN_NAME']))
814
			{
815
				$retval[] = $row['COLUMN_NAME'];
816
			}
817
			else
818
			{
819
				$retval[] = current($row);
820
			}
821
		}
822
 
823
		$this->data_cache['field_names'][$table] = $retval;
824
		return $this->data_cache['field_names'][$table];
825
	}
826
 
827
	// --------------------------------------------------------------------
828
 
829
	/**
830
	 * Determine if a particular field exists
831
	 * @access	public
832
	 * @param	string
833
	 * @param	string
834
	 * @return	boolean
835
	 */
836
	function field_exists($field_name, $table_name)
837
	{
838
		return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
839
	}
840
 
841
	// --------------------------------------------------------------------
842
 
843
	/**
844
	 * Returns an object with field data
845
	 *
846
	 * @access	public
847
	 * @param	string	the table name
848
	 * @return	object
849
	 */
850
	function field_data($table = '')
851
	{
852
		if ($table == '')
853
		{
854
			if ($this->db_debug)
855
			{
856
				return $this->display_error('db_field_param_missing');
857
			}
858
			return FALSE;
859
		}
860
 
861
		$query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE)));
862
 
863
		return $query->field_data();
864
	}
865
 
866
	// --------------------------------------------------------------------
867
 
868
	/**
869
	 * Generate an insert string
870
	 *
871
	 * @access	public
872
	 * @param	string	the table upon which the query will be performed
873
	 * @param	array	an associative array data of key/values
874
	 * @return	string
875
	 */
876
	function insert_string($table, $data)
877
	{
878
		$fields = array();
879
		$values = array();
880
 
881
		foreach($data as $key => $val)
882
		{
883
			$fields[] = $this->_escape_identifiers($key);
884
			$values[] = $this->escape($val);
885
		}
886
 
887
		return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
888
	}
889
 
890
	// --------------------------------------------------------------------
891
 
892
	/**
893
	 * Generate an update string
894
	 *
895
	 * @access	public
896
	 * @param	string	the table upon which the query will be performed
897
	 * @param	array	an associative array data of key/values
898
	 * @param	mixed	the "where" statement
899
	 * @return	string
900
	 */
901
	function update_string($table, $data, $where)
902
	{
903
		if ($where == '')
904
		{
905
			return false;
906
		}
907
 
908
		$fields = array();
909
		foreach($data as $key => $val)
910
		{
911
			$fields[$this->_protect_identifiers($key)] = $this->escape($val);
912
		}
913
 
914
		if ( ! is_array($where))
915
		{
916
			$dest = array($where);
917
		}
918
		else
919
		{
920
			$dest = array();
921
			foreach ($where as $key => $val)
922
			{
923
				$prefix = (count($dest) == 0) ? '' : ' AND ';
924
 
925
				if ($val !== '')
926
				{
927
					if ( ! $this->_has_operator($key))
928
					{
929
						$key .= ' =';
930
					}
931
 
932
					$val = ' '.$this->escape($val);
933
				}
934
 
935
				$dest[] = $prefix.$key.$val;
936
			}
937
		}
938
 
939
		return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest);
940
	}
941
 
942
	// --------------------------------------------------------------------
943
 
944
	/**
945
	 * Tests whether the string has an SQL operator
946
	 *
947
	 * @access	private
948
	 * @param	string
949
	 * @return	bool
950
	 */
951
	function _has_operator($str)
952
	{
953
		$str = trim($str);
954
		if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
955
		{
956
			return FALSE;
957
		}
958
 
959
		return TRUE;
960
	}
961
 
962
	// --------------------------------------------------------------------
963
 
964
	/**
965
	 * 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 ( ! class_exists('CI_DB_Cache'))
1091
		{
1092
			if ( ! @include(BASEPATH.'database/DB_cache'.EXT))
1093
			{
1094
				return $this->cache_off();
1095
			}
1096
		}
1097
 
1098
		$this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
1099
		return TRUE;
1100
	}
1101
 
1102
	// --------------------------------------------------------------------
1103
 
1104
	/**
1105
	 * Close DB Connection
1106
	 *
1107
	 * @access	public
1108
	 * @return	void
1109
	 */
1110
	function close()
1111
	{
1112
		if (is_resource($this->conn_id) OR is_object($this->conn_id))
1113
		{
1114
			$this->_close($this->conn_id);
1115
		}
1116
		$this->conn_id = FALSE;
1117
	}
1118
 
1119
	// --------------------------------------------------------------------
1120
 
1121
	/**
1122
	 * Display an error message
1123
	 *
1124
	 * @access	public
1125
	 * @param	string	the error message
1126
	 * @param	string	any "swap" values
1127
	 * @param	boolean	whether to localize the message
1128
	 * @return	string	sends the application/error_db.php template
1129
	 */
1130
	function display_error($error = '', $swap = '', $native = FALSE)
1131
	{
1132
		$LANG =& load_class('Language');
1133
		$LANG->load('db');
1134
 
1135
		$heading = $LANG->line('db_error_heading');
1136
 
1137
		if ($native == TRUE)
1138
		{
1139
			$message = $error;
1140
		}
1141
		else
1142
		{
1143
			$message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
1144
		}
1145
 
1146
		$error =& load_class('Exceptions');
1147
		echo $error->show_error($heading, $message, 'error_db');
1148
		exit;
1149
	}
1150
 
1151
	// --------------------------------------------------------------------
1152
 
1153
	/**
1154
	 * Protect Identifiers
1155
	 *
1156
	 * This function adds backticks if appropriate based on db type
1157
	 *
1158
	 * @access	private
1159
	 * @param	mixed	the item to escape
1160
	 * @return	mixed	the item with backticks
1161
	 */
1162
	function protect_identifiers($item, $prefix_single = FALSE)
1163
	{
1164
		return $this->_protect_identifiers($item, $prefix_single);
1165
	}
1166
 
1167
	// --------------------------------------------------------------------
1168
 
1169
	/**
1170
	 * Protect Identifiers
1171
	 *
1172
	 * This function is used extensively by the Active Record class, and by
1173
	 * a couple functions in this class.
1174
	 * It takes a column or table name (optionally with an alias) and inserts
1175
	 * the table prefix onto it.  Some logic is necessary in order to deal with
1176
	 * column names that include the path.  Consider a query like this:
1177
	 *
1178
	 * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
1179
	 *
1180
	 * Or a query with aliasing:
1181
	 *
1182
	 * SELECT m.member_id, m.member_name FROM members AS m
1183
	 *
1184
	 * Since the column name can include up to four segments (host, DB, table, column)
1185
	 * or also have an alias prefix, we need to do a bit of work to figure this out and
1186
	 * insert the table prefix (if it exists) in the proper position, and escape only
1187
	 * the correct identifiers.
1188
	 *
1189
	 * @access	private
1190
	 * @param	string
1191
	 * @param	bool
1192
	 * @param	mixed
1193
	 * @param	bool
1194
	 * @return	string
1195
	 */
1196
	function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
1197
	{
1198
		if ( ! is_bool($protect_identifiers))
1199
		{
1200
			$protect_identifiers = $this->_protect_identifiers;
1201
		}
1202
 
1203
		if (is_array($item))
1204
		{
1205
			$escaped_array = array();
1206
 
1207
			foreach($item as $k => $v)
1208
			{
1209
				$escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
1210
			}
1211
 
1212
			return $escaped_array;
1213
		}
1214
 
1215
		// Convert tabs or multiple spaces into single spaces
1216
		$item = preg_replace('/[\t ]+/', ' ', $item);
1217
 
1218
		// If the item has an alias declaration we remove it and set it aside.
1219
		// Basically we remove everything to the right of the first space
1220
		$alias = '';
1221
		if (strpos($item, ' ') !== FALSE)
1222
		{
1223
			$alias = strstr($item, " ");
1224
			$item = substr($item, 0, - strlen($alias));
1225
		}
1226
 
1227
		// This is basically a bug fix for queries that use MAX, MIN, etc.
1228
		// If a parenthesis is found we know that we do not need to
1229
		// escape the data or add a prefix.  There's probably a more graceful
1230
		// way to deal with this, but I'm not thinking of it -- Rick
1231
		if (strpos($item, '(') !== FALSE)
1232
		{
1233
			return $item.$alias;
1234
		}
1235
 
1236
		// Break the string apart if it contains periods, then insert the table prefix
1237
		// in the correct location, assuming the period doesn't indicate that we're dealing
1238
		// with an alias. While we're at it, we will escape the components
1239
		if (strpos($item, '.') !== FALSE)
1240
		{
1241
			$parts	= explode('.', $item);
1242
 
1243
			// Does the first segment of the exploded item match
1244
			// one of the aliases previously identified?  If so,
1245
			// we have nothing more to do other than escape the item
1246
			if (in_array($parts[0], $this->ar_aliased_tables))
1247
			{
1248
				if ($protect_identifiers === TRUE)
1249
				{
1250
					foreach ($parts as $key => $val)
1251
					{
1252
						if ( ! in_array($val, $this->_reserved_identifiers))
1253
						{
1254
							$parts[$key] = $this->_escape_identifiers($val);
1255
						}
1256
					}
1257
 
1258
					$item = implode('.', $parts);
1259
				}
1260
				return $item.$alias;
1261
			}
1262
 
1263
			// Is there a table prefix defined in the config file?  If not, no need to do anything
1264
			if ($this->dbprefix != '')
1265
			{
1266
				// We now add the table prefix based on some logic.
1267
				// Do we have 4 segments (hostname.database.table.column)?
1268
				// If so, we add the table prefix to the column name in the 3rd segment.
1269
				if (isset($parts[3]))
1270
				{
1271
					$i = 2;
1272
				}
1273
				// Do we have 3 segments (database.table.column)?
1274
				// If so, we add the table prefix to the column name in 2nd position
1275
				elseif (isset($parts[2]))
1276
				{
1277
					$i = 1;
1278
				}
1279
				// Do we have 2 segments (table.column)?
1280
				// If so, we add the table prefix to the column name in 1st segment
1281
				else
1282
				{
1283
					$i = 0;
1284
				}
1285
 
1286
				// This flag is set when the supplied $item does not contain a field name.
1287
				// This can happen when this function is being called from a JOIN.
1288
				if ($field_exists == FALSE)
1289
				{
1290
					$i++;
1291
				}
1292
 
1293
				// We only add the table prefix if it does not already exist
1294
				if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
1295
				{
1296
					$parts[$i] = $this->dbprefix.$parts[$i];
1297
				}
1298
 
1299
				// Put the parts back together
1300
				$item = implode('.', $parts);
1301
			}
1302
 
1303
			if ($protect_identifiers === TRUE)
1304
			{
1305
				$item = $this->_escape_identifiers($item);
1306
			}
1307
 
1308
			return $item.$alias;
1309
		}
1310
 
1311
		// Is there a table prefix?  If not, no need to insert it
1312
		if ($this->dbprefix != '')
1313
		{
1314
			// Do we prefix an item with no segments?
1315
			if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
1316
			{
1317
				$item = $this->dbprefix.$item;
1318
			}
1319
		}
1320
 
1321
		if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
1322
		{
1323
			$item = $this->_escape_identifiers($item);
1324
		}
1325
 
1326
		return $item.$alias;
1327
	}
1328
 
1329
 
1330
}
1331
 
1332
 
1333
/* End of file DB_driver.php */
1334
/* Location: ./system/database/DB_driver.php */