blob: 568819a08be61ff204f374703149cbb46538f971 [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
316 $str = substr($str, 1, -1);
Timothy Warren80ab8162011-08-22 18:26:12 -0400317
318 // escape LIKE condition wildcards
319 if ($like === TRUE)
320 {
321 $str = str_replace( array('%', '_', $this->_like_escape_chr),
322 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
323 $str);
324 }
325
326 return $str;
327 }
328
329 // --------------------------------------------------------------------
330
331 /**
332 * Affected Rows
333 *
334 * @access public
335 * @return integer
336 */
337 function affected_rows()
338 {
Timothy Warren51a48882011-09-14 13:47:06 -0400339 return $this->affect_rows;
Timothy Warren80ab8162011-08-22 18:26:12 -0400340 }
341
342 // --------------------------------------------------------------------
343
344 /**
345 * Insert ID
Timothy Warren57cea512011-09-14 14:26:28 -0400346 *
Timothy Warren80ab8162011-08-22 18:26:12 -0400347 * @access public
348 * @return integer
349 */
Timothy Warren51a48882011-09-14 13:47:06 -0400350 function insert_id($name=NULL)
Timothy Warren80ab8162011-08-22 18:26:12 -0400351 {
Timothy Warren51a48882011-09-14 13:47:06 -0400352 return $this->conn_id->lastInsertId($name);
Timothy Warren80ab8162011-08-22 18:26:12 -0400353 }
354
355 // --------------------------------------------------------------------
356
357 /**
358 * "Count All" query
359 *
360 * Generates a platform-specific query string that counts all records in
361 * the specified database
362 *
363 * @access public
364 * @param string
365 * @return string
366 */
367 function count_all($table = '')
368 {
369 if ($table == '')
370 {
371 return 0;
372 }
373
374 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
375
376 if ($query->num_rows() == 0)
377 {
378 return 0;
379 }
380
381 $row = $query->row();
382 $this->_reset_select();
383 return (int) $row->numrows;
384 }
385
386 // --------------------------------------------------------------------
387
388 /**
389 * Show table query
390 *
391 * Generates a platform-specific query string so that the table names can be fetched
392 *
393 * @access private
394 * @param boolean
395 * @return string
396 */
397 function _list_tables($prefix_limit = FALSE)
398 {
399 $sql = "SHOW TABLES FROM `".$this->database."`";
400
401 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
402 {
403 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
404 return FALSE; // not currently supported
405 }
406
407 return $sql;
408 }
409
410 // --------------------------------------------------------------------
411
412 /**
413 * Show column query
414 *
415 * Generates a platform-specific query string so that the column names can be fetched
416 *
417 * @access public
418 * @param string the table name
419 * @return string
420 */
421 function _list_columns($table = '')
422 {
423 return "SHOW COLUMNS FROM ".$table;
424 }
425
426 // --------------------------------------------------------------------
427
428 /**
429 * Field data query
430 *
431 * Generates a platform-specific query so that the column data can be retrieved
432 *
433 * @access public
434 * @param string the table name
435 * @return object
436 */
437 function _field_data($table)
438 {
439 return "SELECT TOP 1 FROM ".$table;
440 }
441
442 // --------------------------------------------------------------------
443
444 /**
445 * The error message string
446 *
447 * @access private
448 * @return string
449 */
450 function _error_message()
451 {
Timothy Warrenab347582011-08-23 12:29:29 -0400452 $error_array = $this->conn_id->errorInfo();
453 return $error_array[2];
Timothy Warren80ab8162011-08-22 18:26:12 -0400454 }
455
456 // --------------------------------------------------------------------
457
458 /**
459 * The error message number
460 *
461 * @access private
462 * @return integer
463 */
464 function _error_number()
465 {
Timothy Warrenab347582011-08-23 12:29:29 -0400466 return $this->conn_id->errorCode();
Timothy Warren80ab8162011-08-22 18:26:12 -0400467 }
468
469 // --------------------------------------------------------------------
470
471 /**
472 * Escape the SQL Identifiers
473 *
474 * This function escapes column and table names
475 *
476 * @access private
477 * @param string
478 * @return string
479 */
480 function _escape_identifiers($item)
481 {
482 if ($this->_escape_char == '')
483 {
484 return $item;
485 }
486
487 foreach ($this->_reserved_identifiers as $id)
488 {
489 if (strpos($item, '.'.$id) !== FALSE)
490 {
491 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
492
493 // remove duplicates if the user already included the escape
494 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
495 }
496 }
497
498 if (strpos($item, '.') !== FALSE)
499 {
500 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
Timothy Warren018af7a2011-09-07 12:07:35 -0400501
Timothy Warren80ab8162011-08-22 18:26:12 -0400502 }
503 else
504 {
505 $str = $this->_escape_char.$item.$this->_escape_char;
506 }
507
508 // remove duplicates if the user already included the escape
509 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
510 }
511
512 // --------------------------------------------------------------------
513
514 /**
515 * From Tables
516 *
517 * This function implicitly groups FROM tables so there is no confusion
518 * about operator precedence in harmony with SQL standards
519 *
520 * @access public
521 * @param type
522 * @return type
523 */
524 function _from_tables($tables)
525 {
526 if ( ! is_array($tables))
527 {
528 $tables = array($tables);
529 }
530
Timothy Warrenab347582011-08-23 12:29:29 -0400531 return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')';
Timothy Warren80ab8162011-08-22 18:26:12 -0400532 }
533
534 // --------------------------------------------------------------------
535
536 /**
537 * Insert statement
538 *
539 * Generates a platform-specific insert string from the supplied data
540 *
541 * @access public
542 * @param string the table name
543 * @param array the insert keys
544 * @param array the insert values
545 * @return string
546 */
547 function _insert($table, $keys, $values)
548 {
549 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
550 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400551
552 // --------------------------------------------------------------------
553
554 /**
555 * Insert_batch statement
556 *
557 * Generates a platform-specific insert string from the supplied data
558 *
559 * @access public
560 * @param string the table name
561 * @param array the insert keys
562 * @param array the insert values
563 * @return string
564 */
565 function _insert_batch($table, $keys, $values)
566 {
567 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
568 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400569
570 // --------------------------------------------------------------------
571
572 /**
573 * Update statement
574 *
575 * Generates a platform-specific update string from the supplied data
576 *
577 * @access public
578 * @param string the table name
579 * @param array the update data
580 * @param array the where clause
581 * @param array the orderby clause
582 * @param array the limit clause
583 * @return string
584 */
585 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
586 {
587 foreach ($values as $key => $val)
588 {
589 $valstr[] = $key." = ".$val;
590 }
591
592 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
593
594 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
595
596 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
597
598 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
599
600 $sql .= $orderby.$limit;
601
602 return $sql;
603 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400604
605 // --------------------------------------------------------------------
606
607 /**
608 * Update_Batch statement
609 *
610 * Generates a platform-specific batch update string from the supplied data
611 *
612 * @access public
613 * @param string the table name
614 * @param array the update data
615 * @param array the where clause
616 * @return string
617 */
618 function _update_batch($table, $values, $index, $where = NULL)
619 {
620 $ids = array();
621 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
622
623 foreach ($values as $key => $val)
624 {
625 $ids[] = $val[$index];
626
627 foreach (array_keys($val) as $field)
628 {
629 if ($field != $index)
630 {
631 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
632 }
633 }
634 }
635
636 $sql = "UPDATE ".$table." SET ";
637 $cases = '';
638
639 foreach ($final as $k => $v)
640 {
641 $cases .= $k.' = CASE '."\n";
642 foreach ($v as $row)
643 {
644 $cases .= $row."\n";
645 }
646
647 $cases .= 'ELSE '.$k.' END, ';
648 }
649
650 $sql .= substr($cases, 0, -2);
651
652 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
653
654 return $sql;
655 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400656
657
658 // --------------------------------------------------------------------
659
660 /**
661 * Truncate statement
662 *
663 * Generates a platform-specific truncate string from the supplied data
664 * If the database does not support the truncate() command
665 * This function maps to "DELETE FROM table"
666 *
667 * @access public
668 * @param string the table name
669 * @return string
670 */
671 function _truncate($table)
672 {
673 return $this->_delete($table);
674 }
675
676 // --------------------------------------------------------------------
677
678 /**
679 * Delete statement
680 *
681 * Generates a platform-specific delete string from the supplied data
682 *
683 * @access public
684 * @param string the table name
685 * @param array the where clause
686 * @param string the limit clause
687 * @return string
688 */
689 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
690 {
691 $conditions = '';
692
693 if (count($where) > 0 OR count($like) > 0)
694 {
695 $conditions = "\nWHERE ";
696 $conditions .= implode("\n", $this->ar_where);
697
698 if (count($where) > 0 && count($like) > 0)
699 {
700 $conditions .= " AND ";
701 }
702 $conditions .= implode("\n", $like);
703 }
704
705 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
706
707 return "DELETE FROM ".$table.$conditions.$limit;
708 }
709
710 // --------------------------------------------------------------------
711
712 /**
713 * Limit string
714 *
715 * Generates a platform-specific LIMIT clause
716 *
717 * @access public
718 * @param string the sql query string
719 * @param integer the number of rows to limit the query to
720 * @param integer the offset value
721 * @return string
722 */
723 function _limit($sql, $limit, $offset)
724 {
Timothy Warren5fc36d82011-09-16 12:31:37 -0400725 if(strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE)
Timothy Warren0a43ad82011-09-15 20:15:19 -0400726 {
727 if ($offset == 0)
728 {
729 $offset = '';
730 }
731 else
732 {
733 $offset .= ", ";
734 }
735
736 return $sql."LIMIT ".$offset.$limit;
737 }
738 else
739 {
740 $sql .= "LIMIT ".$limit;
741
742 if ($offset > 0)
743 {
744 $sql .= " OFFSET ".$offset;
745 }
746
747 return $sql;
748 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400749 }
750
751 // --------------------------------------------------------------------
752
753 /**
754 * Close DB Connection
755 *
756 * @access public
757 * @param resource
758 * @return void
759 */
760 function _close($conn_id)
761 {
Timothy Warren6a450cf2011-08-23 12:46:11 -0400762 $this->conn_id = null;
Timothy Warren80ab8162011-08-22 18:26:12 -0400763 }
764
765
766}
767
768
769
770/* End of file pdo_driver.php */
771/* Location: ./system/database/drivers/pdo/pdo_driver.php */