blob: db04c6de8b103b13e68ba3758059c2d5d97dfc33 [file] [log] [blame]
Derek Jones0b59f272008-05-13 04:22:33 +00001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Derek Allardd2df9bc2007-04-15 17:41:17 +00002/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
Derek Allard3d879d52008-01-18 19:41:32 +00008 * @author ExpressionEngine Dev Team
Rick Ellis9ba2bf22008-09-12 23:34:39 +00009 * @copyright Copyright (c) 2008, EllisLab, Inc.
Derek Jones7a9193a2008-01-21 18:39:20 +000010 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
Derek Allardd2df9bc2007-04-15 17:41:17 +000012 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * MySQL Database Adapter Class
20 *
21 * Note: _DB is an extender class that the app controller
22 * creates dynamically based on whether the active record
23 * class is being used or not.
24 *
25 * @package CodeIgniter
26 * @subpackage Drivers
27 * @category Database
Derek Allard3d879d52008-01-18 19:41:32 +000028 * @author ExpressionEngine Dev Team
Derek Jones7a9193a2008-01-21 18:39:20 +000029 * @link http://codeigniter.com/user_guide/database/
Derek Allardd2df9bc2007-04-15 17:41:17 +000030 */
31class CI_DB_mysql_driver extends CI_DB {
32
Rick Ellis5aa8c602008-10-07 01:24:07 +000033 var $dbdriver = 'mysql';
34
Derek Allardd2df9bc2007-04-15 17:41:17 +000035 /**
36 * Whether to use the MySQL "delete hack" which allows the number
37 * of affected rows to be shown. Uses a preg_replace when enabled,
38 * adding a bit more processing to all queries.
39 */
40 var $delete_hack = TRUE;
Derek Allard6ddb5a12007-12-18 17:22:50 +000041
42 /**
43 * The syntax to count rows is slightly different across different
44 * database engines, so this string appears in each driver and is
45 * used for the count_all() and count_all_results() functions.
46 */
Derek Allard39b622d2008-01-16 21:10:09 +000047 var $_count_string = 'SELECT COUNT(*) AS ';
Derek Allard6ddb5a12007-12-18 17:22:50 +000048 var $_random_keyword = ' RAND()'; // database specific random keyword
Derek Allardd2df9bc2007-04-15 17:41:17 +000049
50 /**
51 * Non-persistent database connection
52 *
53 * @access private called by the base class
54 * @return resource
55 */
56 function db_connect()
57 {
58 return @mysql_connect($this->hostname, $this->username, $this->password, TRUE);
59 }
60
61 // --------------------------------------------------------------------
62
63 /**
64 * Persistent database connection
65 *
66 * @access private called by the base class
67 * @return resource
68 */
69 function db_pconnect()
70 {
71 return @mysql_pconnect($this->hostname, $this->username, $this->password);
72 }
73
74 // --------------------------------------------------------------------
75
76 /**
77 * Select the database
78 *
79 * @access private called by the base class
80 * @return resource
81 */
82 function db_select()
83 {
84 return @mysql_select_db($this->database, $this->conn_id);
85 }
86
87 // --------------------------------------------------------------------
88
89 /**
Derek Allard39b622d2008-01-16 21:10:09 +000090 * Set client character set
91 *
92 * @access public
93 * @param string
94 * @param string
95 * @return resource
96 */
97 function db_set_charset($charset, $collation)
98 {
99 return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id);
100 }
101
102 // --------------------------------------------------------------------
103
104 /**
Derek Allardd2df9bc2007-04-15 17:41:17 +0000105 * Version number query string
106 *
107 * @access public
108 * @return string
109 */
110 function _version()
111 {
112 return "SELECT version() AS ver";
113 }
114
115 // --------------------------------------------------------------------
116
117 /**
118 * Execute the query
119 *
120 * @access private called by the base class
121 * @param string an SQL query
122 * @return resource
123 */
124 function _execute($sql)
125 {
126 $sql = $this->_prep_query($sql);
127 return @mysql_query($sql, $this->conn_id);
128 }
129
130 // --------------------------------------------------------------------
131
132 /**
133 * Prep the query
134 *
135 * If needed, each database adapter can prep the query string
136 *
137 * @access private called by execute()
138 * @param string an SQL query
139 * @return string
140 */
141 function _prep_query($sql)
142 {
143 // "DELETE FROM TABLE" returns 0 affected rows This hack modifies
144 // the query so that it returns the number of affected rows
145 if ($this->delete_hack === TRUE)
146 {
147 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
148 {
149 $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql);
150 }
151 }
152
153 return $sql;
154 }
155
156 // --------------------------------------------------------------------
157
158 /**
159 * Begin Transaction
160 *
161 * @access public
162 * @return bool
163 */
164 function trans_begin($test_mode = FALSE)
165 {
Derek Jones0b59f272008-05-13 04:22:33 +0000166 if ( ! $this->trans_enabled)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000167 {
168 return TRUE;
169 }
170
171 // When transactions are nested we only begin/commit/rollback the outermost ones
172 if ($this->_trans_depth > 0)
173 {
174 return TRUE;
175 }
176
177 // Reset the transaction failure flag.
178 // If the $test_mode flag is set to TRUE transactions will be rolled back
179 // even if the queries produce a successful result.
180 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
181
182 $this->simple_query('SET AUTOCOMMIT=0');
183 $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
184 return TRUE;
185 }
186
187 // --------------------------------------------------------------------
188
189 /**
190 * Commit Transaction
191 *
192 * @access public
193 * @return bool
194 */
195 function trans_commit()
196 {
Derek Jones0b59f272008-05-13 04:22:33 +0000197 if ( ! $this->trans_enabled)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000198 {
199 return TRUE;
200 }
201
202 // When transactions are nested we only begin/commit/rollback the outermost ones
203 if ($this->_trans_depth > 0)
204 {
205 return TRUE;
206 }
207
208 $this->simple_query('COMMIT');
209 $this->simple_query('SET AUTOCOMMIT=1');
210 return TRUE;
211 }
212
213 // --------------------------------------------------------------------
214
215 /**
216 * Rollback Transaction
217 *
218 * @access public
219 * @return bool
220 */
221 function trans_rollback()
222 {
Derek Jones0b59f272008-05-13 04:22:33 +0000223 if ( ! $this->trans_enabled)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000224 {
225 return TRUE;
226 }
227
228 // When transactions are nested we only begin/commit/rollback the outermost ones
229 if ($this->_trans_depth > 0)
230 {
231 return TRUE;
232 }
233
234 $this->simple_query('ROLLBACK');
235 $this->simple_query('SET AUTOCOMMIT=1');
236 return TRUE;
237 }
238
239 // --------------------------------------------------------------------
240
241 /**
242 * Escape String
243 *
244 * @access public
245 * @param string
246 * @return string
247 */
248 function escape_str($str)
249 {
Derek Allard694b5b82007-12-18 15:58:03 +0000250 if (is_array($str))
Derek Allard993925b2008-08-21 12:43:31 +0000251 {
252 foreach($str as $key => $val)
253 {
254 $str[$key] = $this->escape_str($val);
255 }
256
257 return $str;
258 }
259
Derek Allard694b5b82007-12-18 15:58:03 +0000260 if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id))
Derek Allardd2df9bc2007-04-15 17:41:17 +0000261 {
262 return mysql_real_escape_string($str, $this->conn_id);
263 }
264 elseif (function_exists('mysql_escape_string'))
265 {
266 return mysql_escape_string($str);
267 }
268 else
269 {
270 return addslashes($str);
271 }
272 }
273
274 // --------------------------------------------------------------------
275
276 /**
277 * Affected Rows
278 *
279 * @access public
280 * @return integer
281 */
282 function affected_rows()
283 {
284 return @mysql_affected_rows($this->conn_id);
285 }
286
287 // --------------------------------------------------------------------
288
289 /**
290 * Insert ID
291 *
292 * @access public
293 * @return integer
294 */
295 function insert_id()
296 {
297 return @mysql_insert_id($this->conn_id);
298 }
299
300 // --------------------------------------------------------------------
301
302 /**
303 * "Count All" query
304 *
305 * Generates a platform-specific query string that counts all records in
306 * the specified database
307 *
308 * @access public
309 * @param string
310 * @return string
311 */
312 function count_all($table = '')
313 {
314 if ($table == '')
315 return '0';
316
Derek Allardf6cd45c2008-01-18 14:31:51 +0000317 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows'). " FROM " . $this->_protect_identifiers($this->dbprefix.$table));
Derek Allardd2df9bc2007-04-15 17:41:17 +0000318
Rick Ellisff734012008-09-30 20:38:12 +0000319 if ($query->num_rows() == 0)
320 return '0';
321
Derek Allardd2df9bc2007-04-15 17:41:17 +0000322 $row = $query->row();
Derek Allardb94b89c2008-04-28 23:18:00 +0000323 return (int)$row->numrows;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000324 }
325
326 // --------------------------------------------------------------------
327
328 /**
329 * List table query
330 *
331 * Generates a platform-specific query string so that the table names can be fetched
332 *
333 * @access private
Derek Allard39b622d2008-01-16 21:10:09 +0000334 * @param boolean
Derek Allardd2df9bc2007-04-15 17:41:17 +0000335 * @return string
336 */
Derek Allard694b5b82007-12-18 15:58:03 +0000337 function _list_tables($prefix_limit = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000338 {
Derek Allard694b5b82007-12-18 15:58:03 +0000339 $sql = "SHOW TABLES FROM `".$this->database."`";
Derek Allard39b622d2008-01-16 21:10:09 +0000340
341 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
Derek Allard694b5b82007-12-18 15:58:03 +0000342 {
Derek Allard39b622d2008-01-16 21:10:09 +0000343 $sql .= " LIKE '".$this->dbprefix."%'";
Derek Allard694b5b82007-12-18 15:58:03 +0000344 }
Derek Allard39b622d2008-01-16 21:10:09 +0000345
Derek Allard694b5b82007-12-18 15:58:03 +0000346 return $sql;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000347 }
348
349 // --------------------------------------------------------------------
350
351 /**
352 * Show column query
353 *
354 * Generates a platform-specific query string so that the column names can be fetched
355 *
356 * @access public
357 * @param string the table name
358 * @return string
359 */
360 function _list_columns($table = '')
361 {
362 return "SHOW COLUMNS FROM ".$this->_escape_table($table);
363 }
364
365 // --------------------------------------------------------------------
366
367 /**
368 * Field data query
369 *
370 * Generates a platform-specific query so that the column data can be retrieved
371 *
372 * @access public
373 * @param string the table name
374 * @return object
375 */
376 function _field_data($table)
377 {
378 return "SELECT * FROM ".$this->_escape_table($table)." LIMIT 1";
379 }
380
381 // --------------------------------------------------------------------
382
383 /**
384 * The error message string
385 *
386 * @access private
387 * @return string
388 */
389 function _error_message()
390 {
391 return mysql_error($this->conn_id);
392 }
393
394 // --------------------------------------------------------------------
395
396 /**
397 * The error message number
398 *
399 * @access private
400 * @return integer
401 */
402 function _error_number()
403 {
404 return mysql_errno($this->conn_id);
405 }
Rick Ellis52dc8ca2008-09-30 19:53:52 +0000406
407 // --------------------------------------------------------------------
408
409 /**
410 * Escape Column Name
411 *
412 * This function adds backticks around supplied column name
413 *
414 * @access private
415 * @param string the column name
416 * @return string
417 */
418 function _escape_column($column)
419 {
420 return '`' .$column. '`';
421 }
Derek Allardd2df9bc2007-04-15 17:41:17 +0000422
423 // --------------------------------------------------------------------
424
425 /**
426 * Escape Table Name
427 *
428 * This function adds backticks if the table name has a period
429 * in it. Some DBs will get cranky unless periods are escaped
430 *
431 * @access private
432 * @param string the table name
433 * @return string
434 */
435 function _escape_table($table)
436 {
Derek Allard39b622d2008-01-16 21:10:09 +0000437 if (strpos($table, '.') !== FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000438 {
Derek Allardc0743382008-02-11 05:54:44 +0000439 $table = '`' . str_replace('.', '`.`', $table) . '`';
Derek Allardd2df9bc2007-04-15 17:41:17 +0000440 }
441
442 return $table;
443 }
Derek Allard39b622d2008-01-16 21:10:09 +0000444
445 // --------------------------------------------------------------------
446
447 /**
448 * Protect Identifiers
449 *
450 * This function adds backticks if appropriate based on db type
451 *
452 * @access private
453 * @param mixed the item to escape
454 * @param boolean only affect the first word
455 * @return mixed the item with backticks
456 */
457 function _protect_identifiers($item, $first_word_only = FALSE)
458 {
459 if (is_array($item))
460 {
461 $escaped_array = array();
462
463 foreach($item as $k=>$v)
464 {
465 $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v, $first_word_only);
466 }
467
468 return $escaped_array;
469 }
470
471 // This function may get "item1 item2" as a string, and so
472 // we may need "`item1` `item2`" and not "`item1 item2`"
Derek Jones68d021b2008-01-16 21:58:37 +0000473 if (ctype_alnum($item) === FALSE)
Derek Allard39b622d2008-01-16 21:10:09 +0000474 {
Derek Allard9b3e7b52008-02-04 23:20:34 +0000475 if (strpos($item, '.') !== FALSE)
476 {
477 $aliased_tables = implode(".",$this->ar_aliased_tables).'.';
478 $table_name = substr($item, 0, strpos($item, '.')+1);
479 $item = (strpos($aliased_tables, $table_name) !== FALSE) ? $item = $item : $this->dbprefix.$item;
480 }
481
Derek Allard39b622d2008-01-16 21:10:09 +0000482 // This function may get "field >= 1", and need it to return "`field` >= 1"
Derek Jonescdbdf2d2008-01-16 22:18:03 +0000483 $lbound = ($first_word_only === TRUE) ? '' : '|\s|\(';
Derek Allard39b622d2008-01-16 21:10:09 +0000484
Derek Jonescdbdf2d2008-01-16 22:18:03 +0000485 $item = preg_replace('/(^'.$lbound.')([\w\d\-\_]+?)(\s|\)|$)/iS', '$1`$2`$3', $item);
Derek Allard39b622d2008-01-16 21:10:09 +0000486 }
Derek Jones91f50b62008-01-16 21:48:18 +0000487 else
488 {
489 return "`{$item}`";
490 }
Derek Allard39b622d2008-01-16 21:10:09 +0000491
Derek Allard9a4d1da2008-02-25 14:18:38 +0000492 $exceptions = array('AS', '/', '-', '%', '+', '*', 'OR', 'IS');
Derek Allardd2df9bc2007-04-15 17:41:17 +0000493
Derek Allard39b622d2008-01-16 21:10:09 +0000494 foreach ($exceptions as $exception)
495 {
496
497 if (stristr($item, " `{$exception}` ") !== FALSE)
498 {
499 $item = preg_replace('/ `('.preg_quote($exception).')` /i', ' $1 ', $item);
500 }
501 }
502 return $item;
503 }
504
Derek Allardd2df9bc2007-04-15 17:41:17 +0000505 // --------------------------------------------------------------------
506
507 /**
Derek Jonesc6ad0232008-01-29 18:44:54 +0000508 * From Tables
509 *
510 * This function implicitly groups FROM tables so there is no confusion
511 * about operator precedence in harmony with SQL standards
512 *
513 * @access public
514 * @param type
515 * @return type
516 */
517 function _from_tables($tables)
518 {
Derek Jones0b59f272008-05-13 04:22:33 +0000519 if ( ! is_array($tables))
Derek Jonesc6ad0232008-01-29 18:44:54 +0000520 {
521 $tables = array($tables);
522 }
523
524 return '('.implode(', ', $tables).')';
525 }
526
527 // --------------------------------------------------------------------
528
529 /**
Derek Allardd2df9bc2007-04-15 17:41:17 +0000530 * Insert statement
531 *
532 * Generates a platform-specific insert string from the supplied data
533 *
534 * @access public
535 * @param string the table name
536 * @param array the insert keys
537 * @param array the insert values
538 * @return string
539 */
540 function _insert($table, $keys, $values)
541 {
542 return "INSERT INTO ".$this->_escape_table($table)." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
543 }
544
545 // --------------------------------------------------------------------
546
547 /**
548 * Update statement
549 *
550 * Generates a platform-specific update string from the supplied data
551 *
552 * @access public
553 * @param string the table name
554 * @param array the update data
555 * @param array the where clause
Derek Allard39b622d2008-01-16 21:10:09 +0000556 * @param array the orderby clause
557 * @param array the limit clause
Derek Allardd2df9bc2007-04-15 17:41:17 +0000558 * @return string
559 */
Derek Allard39b622d2008-01-16 21:10:09 +0000560 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000561 {
562 foreach($values as $key => $val)
563 {
564 $valstr[] = $key." = ".$val;
565 }
Derek Allardda6d2402007-12-19 14:49:29 +0000566
Derek Jones0b59f272008-05-13 04:22:33 +0000567 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
Derek Allard39b622d2008-01-16 21:10:09 +0000568
569 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
Derek Allardd2df9bc2007-04-15 17:41:17 +0000570
Derek Allard32cf7eb2008-02-05 16:03:50 +0000571 $sql = "UPDATE ".$this->_escape_table($table)." SET ".implode(', ', $valstr);
572 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
573 $sql .= $orderby.$limit;
574
575 return $sql;
Derek Allard39b622d2008-01-16 21:10:09 +0000576 }
577
578 // --------------------------------------------------------------------
579
580 /**
581 * Truncate statement
582 *
583 * Generates a platform-specific truncate string from the supplied data
584 * If the database does not support the truncate() command
585 * This function maps to "DELETE FROM table"
586 *
587 * @access public
588 * @param string the table name
589 * @return string
590 */
591 function _truncate($table)
592 {
593 return "TRUNCATE ".$this->_escape_table($table);
Derek Allardd2df9bc2007-04-15 17:41:17 +0000594 }
595
596 // --------------------------------------------------------------------
597
598 /**
599 * Delete statement
600 *
601 * Generates a platform-specific delete string from the supplied data
602 *
603 * @access public
604 * @param string the table name
605 * @param array the where clause
Derek Allard39b622d2008-01-16 21:10:09 +0000606 * @param string the limit clause
Derek Allardd2df9bc2007-04-15 17:41:17 +0000607 * @return string
608 */
Derek Allard39b622d2008-01-16 21:10:09 +0000609 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
Derek Allardd2df9bc2007-04-15 17:41:17 +0000610 {
Derek Allard39b622d2008-01-16 21:10:09 +0000611 $conditions = '';
612
Derek Jones0b59f272008-05-13 04:22:33 +0000613 if (count($where) > 0 OR count($like) > 0)
Derek Allard39b622d2008-01-16 21:10:09 +0000614 {
615 $conditions = "\nWHERE ";
616 $conditions .= implode("\n", $this->ar_where);
617
618 if (count($where) > 0 && count($like) > 0)
619 {
620 $conditions .= " AND ";
621 }
622 $conditions .= implode("\n", $like);
623 }
624
Derek Jones0b59f272008-05-13 04:22:33 +0000625 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
Derek Allarde77d77c2007-12-19 15:01:55 +0000626
Derek Allard39b622d2008-01-16 21:10:09 +0000627 return "DELETE FROM ".$table.$conditions.$limit;
Derek Allardd2df9bc2007-04-15 17:41:17 +0000628 }
629
630 // --------------------------------------------------------------------
631
632 /**
633 * Limit string
634 *
635 * Generates a platform-specific LIMIT clause
636 *
637 * @access public
638 * @param string the sql query string
639 * @param integer the number of rows to limit the query to
640 * @param integer the offset value
641 * @return string
642 */
643 function _limit($sql, $limit, $offset)
644 {
645 if ($offset == 0)
646 {
647 $offset = '';
648 }
649 else
650 {
651 $offset .= ", ";
652 }
653
654 return $sql."LIMIT ".$offset.$limit;
655 }
656
657 // --------------------------------------------------------------------
658
659 /**
660 * Close DB Connection
661 *
662 * @access public
663 * @param resource
664 * @return void
665 */
666 function _close($conn_id)
667 {
668 @mysql_close($conn_id);
669 }
670
671}
672
Derek Jones0b59f272008-05-13 04:22:33 +0000673
674/* End of file mysql_driver.php */
Derek Jonesa3ffbbb2008-05-11 18:18:29 +0000675/* Location: ./system/database/drivers/mysql/mysql_driver.php */