blob: 750c02e274573c5ec187d8014c4c482190477b4e [file] [log] [blame]
Timothy Warren80ab8162011-08-22 18:26:12 -04001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.1.6 or newer
6 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
Timothy Warren018af7a2011-09-07 12:07:35 -040012 * @since Version 2.1.0
Timothy Warren80ab8162011-08-22 18:26:12 -040013 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
Timothy Warren02615962011-08-24 08:21:36 -040019 * PDO Database Adapter Class
Timothy Warren80ab8162011-08-22 18:26:12 -040020 *
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
28 * @author ExpressionEngine Dev Team
29 * @link http://codeigniter.com/user_guide/database/
30 */
31class CI_DB_pdo_driver extends CI_DB {
32
33 var $dbdriver = 'pdo';
34
35 // the character used to excape - not necessary for PDO
36 var $_escape_char = '';
Timothy Warrenc7ba6642011-09-14 12:25:14 -040037 var $_like_escape_str;
38 var $_like_escape_chr;
39
Timothy Warren80ab8162011-08-22 18:26:12 -040040
41 /**
42 * The syntax to count rows is slightly different across different
43 * database engines, so this string appears in each driver and is
44 * used for the count_all() and count_all_results() functions.
45 */
46 var $_count_string = "SELECT COUNT(*) AS ";
47 var $_random_keyword;
48
49
Timothy Warren51b0e642011-09-13 13:30:27 -040050 function __construct($params)
Timothy Warren80ab8162011-08-22 18:26:12 -040051 {
Timothy Warrenb5a43b02011-10-04 17:26:04 -040052 parent::__construct($params);
Timothy Warrenab347582011-08-23 12:29:29 -040053
Timothy Warrenc7ba6642011-09-14 12:25:14 -040054 // clause and character used for LIKE escape sequences
55 if(strpos($this->hostname, 'mysql') !== FALSE)
56 {
57 $this->_like_escape_str = '';
58 $this->_like_escape_chr = '';
59 }
60 else if(strpos($this->hostname, 'odbc') !== FALSE)
61 {
62 $this->_like_escape_str = " {escape '%s'} ";
63 $this->_like_escape_chr = '!';
64 }
65 else
66 {
67 $this->_like_escape_str = " ESCAPE '%s' ";
68 $this->_like_escape_chr = '!';
69 }
70
Timothy Warrenab347582011-08-23 12:29:29 -040071 $this->hostname = $this->hostname . ";dbname=".$this->database;
72 $this->trans_enabled = FALSE;
Timothy Warren80ab8162011-08-22 18:26:12 -040073
74 $this->_random_keyword = ' RND('.time().')'; // database specific random keyword
75 }
76
77 /**
78 * Non-persistent database connection
79 *
80 * @access private called by the base class
81 * @return resource
82 */
83 function db_connect()
84 {
Timothy Warrenab347582011-08-23 12:29:29 -040085 return new PDO($this->hostname,$this->username,$this->password, array(
86 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
Timothy Warren80ab8162011-08-22 18:26:12 -040087 ));
88 }
89
90 // --------------------------------------------------------------------
91
92 /**
93 * Persistent database connection
94 *
95 * @access private called by the base class
96 * @return resource
97 */
98 function db_pconnect()
99 {
Timothy Warrenab347582011-08-23 12:29:29 -0400100 return new PDO($this->hostname,$this->username,$this->password, array(
101 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
102 PDO::ATTR_PERSISTENT => true
Timothy Warren80ab8162011-08-22 18:26:12 -0400103 ));
104 }
105
106 // --------------------------------------------------------------------
107
108 /**
109 * Reconnect
110 *
111 * Keep / reestablish the db connection if no queries have been
112 * sent for a length of time exceeding the server's idle timeout
113 *
114 * @access public
115 * @return void
116 */
117 function reconnect()
118 {
Timothy Warren02615962011-08-24 08:21:36 -0400119 if ($this->db->db_debug)
120 {
121 return $this->db->display_error('db_unsuported_feature');
122 }
123 return FALSE;
Timothy Warren80ab8162011-08-22 18:26:12 -0400124 }
125
126 // --------------------------------------------------------------------
127
128 /**
129 * Select the database
130 *
131 * @access private called by the base class
132 * @return resource
133 */
134 function db_select()
135 {
136 // Not needed for PDO
137 return TRUE;
138 }
139
140 // --------------------------------------------------------------------
141
142 /**
143 * Set client character set
144 *
145 * @access public
146 * @param string
147 * @param string
148 * @return resource
149 */
150 function db_set_charset($charset, $collation)
151 {
152 // @todo - add support if needed
153 return TRUE;
154 }
155
156 // --------------------------------------------------------------------
157
158 /**
159 * Version number query string
160 *
161 * @access public
162 * @return string
163 */
164 function _version()
165 {
Timothy Warren36fb8de2011-08-24 08:29:05 -0400166 return $this->conn_id->getAttribute(PDO::ATTR_CLIENT_VERSION);
Timothy Warren80ab8162011-08-22 18:26:12 -0400167 }
168
169 // --------------------------------------------------------------------
170
171 /**
172 * Execute the query
173 *
174 * @access private called by the base class
175 * @param string an SQL query
Timothy Warren51a48882011-09-14 13:47:06 -0400176 * @return object
Timothy Warren80ab8162011-08-22 18:26:12 -0400177 */
178 function _execute($sql)
179 {
180 $sql = $this->_prep_query($sql);
Timothy Warren51a48882011-09-14 13:47:06 -0400181 $result_id = $this->conn_id->query($sql);
182
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400183 if(is_object($result_id))
184 {
185 $this->affect_rows = $result_id->rowCount();
186 }
187 else
188 {
189 $this->affect_rows = 0;
190 }
Timothy Warren51a48882011-09-14 13:47:06 -0400191
192 return $result_id;
Timothy Warren80ab8162011-08-22 18:26:12 -0400193 }
194
195 // --------------------------------------------------------------------
196
197 /**
198 * Prep the query
199 *
200 * If needed, each database adapter can prep the query string
201 *
202 * @access private called by execute()
203 * @param string an SQL query
204 * @return string
205 */
206 function _prep_query($sql)
207 {
208 return $sql;
209 }
210
211 // --------------------------------------------------------------------
212
213 /**
214 * Begin Transaction
215 *
216 * @access public
217 * @return bool
218 */
219 function trans_begin($test_mode = FALSE)
220 {
221 if ( ! $this->trans_enabled)
222 {
223 return TRUE;
224 }
225
226 // When transactions are nested we only begin/commit/rollback the outermost ones
227 if ($this->_trans_depth > 0)
228 {
229 return TRUE;
230 }
231
232 // Reset the transaction failure flag.
233 // If the $test_mode flag is set to TRUE transactions will be rolled back
234 // even if the queries produce a successful result.
235 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
236
Timothy Warrenab347582011-08-23 12:29:29 -0400237 return $this->conn_id->beginTransaction();
Timothy Warren80ab8162011-08-22 18:26:12 -0400238 }
239
240 // --------------------------------------------------------------------
241
242 /**
243 * Commit Transaction
244 *
245 * @access public
246 * @return bool
247 */
248 function trans_commit()
249 {
250 if ( ! $this->trans_enabled)
251 {
252 return TRUE;
253 }
254
255 // When transactions are nested we only begin/commit/rollback the outermost ones
256 if ($this->_trans_depth > 0)
257 {
258 return TRUE;
259 }
260
Timothy Warrenab347582011-08-23 12:29:29 -0400261 $ret = $this->conn->commit();
Timothy Warren80ab8162011-08-22 18:26:12 -0400262 return $ret;
263 }
264
265 // --------------------------------------------------------------------
266
267 /**
268 * Rollback Transaction
269 *
270 * @access public
271 * @return bool
272 */
273 function trans_rollback()
274 {
275 if ( ! $this->trans_enabled)
276 {
277 return TRUE;
278 }
279
280 // When transactions are nested we only begin/commit/rollback the outermost ones
281 if ($this->_trans_depth > 0)
282 {
283 return TRUE;
284 }
285
Timothy Warrenab347582011-08-23 12:29:29 -0400286 $ret = $this->conn_id->rollBack();
Timothy Warren80ab8162011-08-22 18:26:12 -0400287 return $ret;
288 }
289
290 // --------------------------------------------------------------------
291
292 /**
293 * Escape String
294 *
295 * @access public
296 * @param string
297 * @param bool whether or not the string will be used in a LIKE condition
298 * @return string
299 */
300 function escape_str($str, $like = FALSE)
301 {
302 if (is_array($str))
303 {
304 foreach ($str as $key => $val)
305 {
306 $str[$key] = $this->escape_str($val, $like);
307 }
308
309 return $str;
310 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400311
Timothy Warren47663972011-10-05 16:44:50 -0400312 //Escape the string
313 $str = $this->conn_id->quote($str);
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400314
Timothy Warren47663972011-10-05 16:44:50 -0400315 //If there are duplicated quotes, trim them away
Timothy Warren0e762b32011-10-07 09:21:40 -0400316 if(strpos($str, "'") === 0)
317 {
318 $str = substr($str, 1, -1);
319 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400320
321 // escape LIKE condition wildcards
322 if ($like === TRUE)
323 {
324 $str = str_replace( array('%', '_', $this->_like_escape_chr),
325 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
326 $str);
327 }
328
329 return $str;
330 }
331
332 // --------------------------------------------------------------------
333
334 /**
335 * Affected Rows
336 *
337 * @access public
338 * @return integer
339 */
340 function affected_rows()
341 {
Timothy Warren51a48882011-09-14 13:47:06 -0400342 return $this->affect_rows;
Timothy Warren80ab8162011-08-22 18:26:12 -0400343 }
344
345 // --------------------------------------------------------------------
346
347 /**
348 * Insert ID
Timothy Warren57cea512011-09-14 14:26:28 -0400349 *
Timothy Warren80ab8162011-08-22 18:26:12 -0400350 * @access public
351 * @return integer
352 */
Timothy Warren51a48882011-09-14 13:47:06 -0400353 function insert_id($name=NULL)
Timothy Warren80ab8162011-08-22 18:26:12 -0400354 {
Timothy Warren0e762b32011-10-07 09:21:40 -0400355 return $this->conn_id->lastInsertId($name);
Timothy Warren80ab8162011-08-22 18:26:12 -0400356 }
357
358 // --------------------------------------------------------------------
359
360 /**
361 * "Count All" query
362 *
363 * Generates a platform-specific query string that counts all records in
364 * the specified database
365 *
366 * @access public
367 * @param string
368 * @return string
369 */
370 function count_all($table = '')
371 {
372 if ($table == '')
373 {
374 return 0;
375 }
376
377 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
378
379 if ($query->num_rows() == 0)
380 {
381 return 0;
382 }
383
384 $row = $query->row();
385 $this->_reset_select();
386 return (int) $row->numrows;
387 }
388
389 // --------------------------------------------------------------------
390
391 /**
392 * Show table query
393 *
394 * Generates a platform-specific query string so that the table names can be fetched
395 *
396 * @access private
397 * @param boolean
398 * @return string
399 */
400 function _list_tables($prefix_limit = FALSE)
401 {
402 $sql = "SHOW TABLES FROM `".$this->database."`";
403
404 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
405 {
Timothy Warren80ab8162011-08-22 18:26:12 -0400406 return FALSE; // not currently supported
407 }
408
409 return $sql;
410 }
411
412 // --------------------------------------------------------------------
413
414 /**
415 * Show column query
416 *
417 * Generates a platform-specific query string so that the column names can be fetched
418 *
419 * @access public
420 * @param string the table name
421 * @return string
422 */
423 function _list_columns($table = '')
424 {
425 return "SHOW COLUMNS FROM ".$table;
426 }
427
428 // --------------------------------------------------------------------
429
430 /**
431 * Field data query
432 *
433 * Generates a platform-specific query so that the column data can be retrieved
434 *
435 * @access public
436 * @param string the table name
437 * @return object
438 */
439 function _field_data($table)
440 {
441 return "SELECT TOP 1 FROM ".$table;
442 }
443
444 // --------------------------------------------------------------------
445
446 /**
447 * The error message string
448 *
449 * @access private
450 * @return string
451 */
452 function _error_message()
453 {
Timothy Warrenab347582011-08-23 12:29:29 -0400454 $error_array = $this->conn_id->errorInfo();
455 return $error_array[2];
Timothy Warren80ab8162011-08-22 18:26:12 -0400456 }
457
458 // --------------------------------------------------------------------
459
460 /**
461 * The error message number
462 *
463 * @access private
464 * @return integer
465 */
466 function _error_number()
467 {
Timothy Warrenab347582011-08-23 12:29:29 -0400468 return $this->conn_id->errorCode();
Timothy Warren80ab8162011-08-22 18:26:12 -0400469 }
470
471 // --------------------------------------------------------------------
472
473 /**
474 * Escape the SQL Identifiers
475 *
476 * This function escapes column and table names
477 *
478 * @access private
479 * @param string
480 * @return string
481 */
482 function _escape_identifiers($item)
483 {
484 if ($this->_escape_char == '')
485 {
486 return $item;
487 }
488
489 foreach ($this->_reserved_identifiers as $id)
490 {
491 if (strpos($item, '.'.$id) !== FALSE)
492 {
493 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
494
495 // remove duplicates if the user already included the escape
496 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
497 }
498 }
499
500 if (strpos($item, '.') !== FALSE)
501 {
502 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
Timothy Warren018af7a2011-09-07 12:07:35 -0400503
Timothy Warren80ab8162011-08-22 18:26:12 -0400504 }
505 else
506 {
507 $str = $this->_escape_char.$item.$this->_escape_char;
508 }
509
510 // remove duplicates if the user already included the escape
511 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
512 }
513
514 // --------------------------------------------------------------------
515
516 /**
517 * From Tables
518 *
519 * This function implicitly groups FROM tables so there is no confusion
520 * about operator precedence in harmony with SQL standards
521 *
522 * @access public
523 * @param type
524 * @return type
525 */
526 function _from_tables($tables)
527 {
528 if ( ! is_array($tables))
529 {
530 $tables = array($tables);
531 }
532
Timothy Warrenab347582011-08-23 12:29:29 -0400533 return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')';
Timothy Warren80ab8162011-08-22 18:26:12 -0400534 }
535
536 // --------------------------------------------------------------------
537
538 /**
539 * Insert statement
540 *
541 * Generates a platform-specific insert string from the supplied data
542 *
543 * @access public
544 * @param string the table name
545 * @param array the insert keys
546 * @param array the insert values
547 * @return string
548 */
549 function _insert($table, $keys, $values)
550 {
551 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
552 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400553
554 // --------------------------------------------------------------------
555
556 /**
557 * Insert_batch statement
558 *
559 * Generates a platform-specific insert string from the supplied data
560 *
561 * @access public
562 * @param string the table name
563 * @param array the insert keys
564 * @param array the insert values
565 * @return string
566 */
567 function _insert_batch($table, $keys, $values)
568 {
569 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
570 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400571
572 // --------------------------------------------------------------------
573
574 /**
575 * Update statement
576 *
577 * Generates a platform-specific update string from the supplied data
578 *
579 * @access public
580 * @param string the table name
581 * @param array the update data
582 * @param array the where clause
583 * @param array the orderby clause
584 * @param array the limit clause
585 * @return string
586 */
587 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
588 {
589 foreach ($values as $key => $val)
590 {
591 $valstr[] = $key." = ".$val;
592 }
593
594 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
595
596 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
597
598 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
599
600 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
601
602 $sql .= $orderby.$limit;
603
604 return $sql;
605 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400606
607 // --------------------------------------------------------------------
608
609 /**
610 * Update_Batch statement
611 *
612 * Generates a platform-specific batch update string from the supplied data
613 *
614 * @access public
615 * @param string the table name
616 * @param array the update data
617 * @param array the where clause
618 * @return string
619 */
620 function _update_batch($table, $values, $index, $where = NULL)
621 {
622 $ids = array();
623 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
624
625 foreach ($values as $key => $val)
626 {
627 $ids[] = $val[$index];
628
629 foreach (array_keys($val) as $field)
630 {
631 if ($field != $index)
632 {
633 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
634 }
635 }
636 }
637
638 $sql = "UPDATE ".$table." SET ";
639 $cases = '';
640
641 foreach ($final as $k => $v)
642 {
643 $cases .= $k.' = CASE '."\n";
644 foreach ($v as $row)
645 {
646 $cases .= $row."\n";
647 }
648
649 $cases .= 'ELSE '.$k.' END, ';
650 }
651
652 $sql .= substr($cases, 0, -2);
653
654 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
655
656 return $sql;
657 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400658
659
660 // --------------------------------------------------------------------
661
662 /**
663 * Truncate statement
664 *
665 * Generates a platform-specific truncate string from the supplied data
666 * If the database does not support the truncate() command
667 * This function maps to "DELETE FROM table"
668 *
669 * @access public
670 * @param string the table name
671 * @return string
672 */
673 function _truncate($table)
674 {
675 return $this->_delete($table);
676 }
677
678 // --------------------------------------------------------------------
679
680 /**
681 * Delete statement
682 *
683 * Generates a platform-specific delete string from the supplied data
684 *
685 * @access public
686 * @param string the table name
687 * @param array the where clause
688 * @param string the limit clause
689 * @return string
690 */
691 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
692 {
693 $conditions = '';
694
695 if (count($where) > 0 OR count($like) > 0)
696 {
697 $conditions = "\nWHERE ";
698 $conditions .= implode("\n", $this->ar_where);
699
700 if (count($where) > 0 && count($like) > 0)
701 {
702 $conditions .= " AND ";
703 }
704 $conditions .= implode("\n", $like);
705 }
706
707 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
708
709 return "DELETE FROM ".$table.$conditions.$limit;
710 }
711
712 // --------------------------------------------------------------------
713
714 /**
715 * Limit string
716 *
717 * Generates a platform-specific LIMIT clause
718 *
719 * @access public
720 * @param string the sql query string
721 * @param integer the number of rows to limit the query to
722 * @param integer the offset value
723 * @return string
724 */
725 function _limit($sql, $limit, $offset)
726 {
Timothy Warren5fc36d82011-09-16 12:31:37 -0400727 if(strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE)
Timothy Warren0a43ad82011-09-15 20:15:19 -0400728 {
729 if ($offset == 0)
730 {
731 $offset = '';
732 }
733 else
734 {
735 $offset .= ", ";
736 }
737
738 return $sql."LIMIT ".$offset.$limit;
739 }
740 else
741 {
742 $sql .= "LIMIT ".$limit;
743
744 if ($offset > 0)
745 {
746 $sql .= " OFFSET ".$offset;
747 }
748
749 return $sql;
750 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400751 }
752
753 // --------------------------------------------------------------------
754
755 /**
756 * Close DB Connection
757 *
758 * @access public
759 * @param resource
760 * @return void
761 */
762 function _close($conn_id)
763 {
Timothy Warren6a450cf2011-08-23 12:46:11 -0400764 $this->conn_id = null;
Timothy Warren80ab8162011-08-22 18:26:12 -0400765 }
766
767
768}
769
770
771
772/* End of file pdo_driver.php */
773/* Location: ./system/database/drivers/pdo/pdo_driver.php */