blob: 1a84404bbc2bad2e1f97c3bcd4d96f47f7e3fd4f [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 Warren33512752011-10-07 09:51:49 -0400316 $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 Warren33512752011-10-07 09:51:49 -0400352 //Convenience method for postgres insertid
353 if(strpos($this->hostname, 'pgsql') !== FALSE)
354 {
355 $v = $this->_version();
356
357 $table = func_num_args() > 0 ? func_get_arg(0) : NULL;
358
359 if ($table == NULL && $v >= '8.1')
360 {
361 $sql='SELECT LASTVAL() as ins_id';
362 }
363 $query = $this->query($sql);
364 $row = $query->row();
365 return $row->ins_id;
366 }
367 else
368 {
369 return $this->conn_id->lastInsertId($name);
370 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400371 }
372
373 // --------------------------------------------------------------------
374
375 /**
376 * "Count All" query
377 *
378 * Generates a platform-specific query string that counts all records in
379 * the specified database
380 *
381 * @access public
382 * @param string
383 * @return string
384 */
385 function count_all($table = '')
386 {
387 if ($table == '')
388 {
389 return 0;
390 }
391
392 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
393
394 if ($query->num_rows() == 0)
395 {
396 return 0;
397 }
398
399 $row = $query->row();
400 $this->_reset_select();
401 return (int) $row->numrows;
402 }
403
404 // --------------------------------------------------------------------
405
406 /**
407 * Show table query
408 *
409 * Generates a platform-specific query string so that the table names can be fetched
410 *
411 * @access private
412 * @param boolean
413 * @return string
414 */
415 function _list_tables($prefix_limit = FALSE)
416 {
417 $sql = "SHOW TABLES FROM `".$this->database."`";
418
419 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
420 {
Timothy Warren33512752011-10-07 09:51:49 -0400421 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
Timothy Warren80ab8162011-08-22 18:26:12 -0400422 return FALSE; // not currently supported
423 }
424
425 return $sql;
426 }
427
428 // --------------------------------------------------------------------
429
430 /**
431 * Show column query
432 *
433 * Generates a platform-specific query string so that the column names can be fetched
434 *
435 * @access public
436 * @param string the table name
437 * @return string
438 */
439 function _list_columns($table = '')
440 {
441 return "SHOW COLUMNS FROM ".$table;
442 }
443
444 // --------------------------------------------------------------------
445
446 /**
447 * Field data query
448 *
449 * Generates a platform-specific query so that the column data can be retrieved
450 *
451 * @access public
452 * @param string the table name
453 * @return object
454 */
455 function _field_data($table)
456 {
457 return "SELECT TOP 1 FROM ".$table;
458 }
459
460 // --------------------------------------------------------------------
461
462 /**
463 * The error message string
464 *
465 * @access private
466 * @return string
467 */
468 function _error_message()
469 {
Timothy Warrenab347582011-08-23 12:29:29 -0400470 $error_array = $this->conn_id->errorInfo();
471 return $error_array[2];
Timothy Warren80ab8162011-08-22 18:26:12 -0400472 }
473
474 // --------------------------------------------------------------------
475
476 /**
477 * The error message number
478 *
479 * @access private
480 * @return integer
481 */
482 function _error_number()
483 {
Timothy Warrenab347582011-08-23 12:29:29 -0400484 return $this->conn_id->errorCode();
Timothy Warren80ab8162011-08-22 18:26:12 -0400485 }
486
487 // --------------------------------------------------------------------
488
489 /**
490 * Escape the SQL Identifiers
491 *
492 * This function escapes column and table names
493 *
494 * @access private
495 * @param string
496 * @return string
497 */
498 function _escape_identifiers($item)
499 {
500 if ($this->_escape_char == '')
501 {
502 return $item;
503 }
504
505 foreach ($this->_reserved_identifiers as $id)
506 {
507 if (strpos($item, '.'.$id) !== FALSE)
508 {
509 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
510
511 // remove duplicates if the user already included the escape
512 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
513 }
514 }
515
516 if (strpos($item, '.') !== FALSE)
517 {
518 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
Timothy Warren018af7a2011-09-07 12:07:35 -0400519
Timothy Warren80ab8162011-08-22 18:26:12 -0400520 }
521 else
522 {
523 $str = $this->_escape_char.$item.$this->_escape_char;
524 }
525
526 // remove duplicates if the user already included the escape
527 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
528 }
529
530 // --------------------------------------------------------------------
531
532 /**
533 * From Tables
534 *
535 * This function implicitly groups FROM tables so there is no confusion
536 * about operator precedence in harmony with SQL standards
537 *
538 * @access public
539 * @param type
540 * @return type
541 */
542 function _from_tables($tables)
543 {
544 if ( ! is_array($tables))
545 {
546 $tables = array($tables);
547 }
548
Timothy Warrenab347582011-08-23 12:29:29 -0400549 return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')';
Timothy Warren80ab8162011-08-22 18:26:12 -0400550 }
551
552 // --------------------------------------------------------------------
553
554 /**
555 * Insert 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($table, $keys, $values)
566 {
567 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
568 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400569
570 // --------------------------------------------------------------------
571
572 /**
573 * Insert_batch statement
574 *
575 * Generates a platform-specific insert string from the supplied data
576 *
577 * @access public
578 * @param string the table name
579 * @param array the insert keys
580 * @param array the insert values
581 * @return string
582 */
583 function _insert_batch($table, $keys, $values)
584 {
585 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
586 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400587
588 // --------------------------------------------------------------------
589
590 /**
591 * Update statement
592 *
593 * Generates a platform-specific update string from the supplied data
594 *
595 * @access public
596 * @param string the table name
597 * @param array the update data
598 * @param array the where clause
599 * @param array the orderby clause
600 * @param array the limit clause
601 * @return string
602 */
603 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
604 {
605 foreach ($values as $key => $val)
606 {
607 $valstr[] = $key." = ".$val;
608 }
609
610 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
611
612 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
613
614 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
615
616 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
617
618 $sql .= $orderby.$limit;
619
620 return $sql;
621 }
Timothy Warrenb5a43b02011-10-04 17:26:04 -0400622
623 // --------------------------------------------------------------------
624
625 /**
626 * Update_Batch statement
627 *
628 * Generates a platform-specific batch update string from the supplied data
629 *
630 * @access public
631 * @param string the table name
632 * @param array the update data
633 * @param array the where clause
634 * @return string
635 */
636 function _update_batch($table, $values, $index, $where = NULL)
637 {
638 $ids = array();
639 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
640
641 foreach ($values as $key => $val)
642 {
643 $ids[] = $val[$index];
644
645 foreach (array_keys($val) as $field)
646 {
647 if ($field != $index)
648 {
649 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
650 }
651 }
652 }
653
654 $sql = "UPDATE ".$table." SET ";
655 $cases = '';
656
657 foreach ($final as $k => $v)
658 {
659 $cases .= $k.' = CASE '."\n";
660 foreach ($v as $row)
661 {
662 $cases .= $row."\n";
663 }
664
665 $cases .= 'ELSE '.$k.' END, ';
666 }
667
668 $sql .= substr($cases, 0, -2);
669
670 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
671
672 return $sql;
673 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400674
675
676 // --------------------------------------------------------------------
677
678 /**
679 * Truncate statement
680 *
681 * Generates a platform-specific truncate string from the supplied data
682 * If the database does not support the truncate() command
683 * This function maps to "DELETE FROM table"
684 *
685 * @access public
686 * @param string the table name
687 * @return string
688 */
689 function _truncate($table)
690 {
691 return $this->_delete($table);
692 }
693
694 // --------------------------------------------------------------------
695
696 /**
697 * Delete statement
698 *
699 * Generates a platform-specific delete string from the supplied data
700 *
701 * @access public
702 * @param string the table name
703 * @param array the where clause
704 * @param string the limit clause
705 * @return string
706 */
707 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
708 {
709 $conditions = '';
710
711 if (count($where) > 0 OR count($like) > 0)
712 {
713 $conditions = "\nWHERE ";
714 $conditions .= implode("\n", $this->ar_where);
715
716 if (count($where) > 0 && count($like) > 0)
717 {
718 $conditions .= " AND ";
719 }
720 $conditions .= implode("\n", $like);
721 }
722
723 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
724
725 return "DELETE FROM ".$table.$conditions.$limit;
726 }
727
728 // --------------------------------------------------------------------
729
730 /**
731 * Limit string
732 *
733 * Generates a platform-specific LIMIT clause
734 *
735 * @access public
736 * @param string the sql query string
737 * @param integer the number of rows to limit the query to
738 * @param integer the offset value
739 * @return string
740 */
741 function _limit($sql, $limit, $offset)
742 {
Timothy Warren5fc36d82011-09-16 12:31:37 -0400743 if(strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE)
Timothy Warren0a43ad82011-09-15 20:15:19 -0400744 {
745 if ($offset == 0)
746 {
747 $offset = '';
748 }
749 else
750 {
751 $offset .= ", ";
752 }
753
754 return $sql."LIMIT ".$offset.$limit;
755 }
756 else
757 {
758 $sql .= "LIMIT ".$limit;
759
760 if ($offset > 0)
761 {
762 $sql .= " OFFSET ".$offset;
763 }
764
765 return $sql;
766 }
Timothy Warren80ab8162011-08-22 18:26:12 -0400767 }
768
769 // --------------------------------------------------------------------
770
771 /**
772 * Close DB Connection
773 *
774 * @access public
775 * @param resource
776 * @return void
777 */
778 function _close($conn_id)
779 {
Timothy Warren6a450cf2011-08-23 12:46:11 -0400780 $this->conn_id = null;
Timothy Warren80ab8162011-08-22 18:26:12 -0400781 }
782
783
784}
785
786
787
788/* End of file pdo_driver.php */
789/* Location: ./system/database/drivers/pdo/pdo_driver.php */