blob: e536cc4bf7d264d2ab284d7937481f3543016b46 [file] [log] [blame]
Timothy Warren24f325c2011-10-07 10:03:01 -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
12 * @since Version 2.1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * PDO 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
28 * @author ExpressionEngine Dev Team
29 * @link http://codeigniter.com/user_guide/database/
30 */
Timothy Warren9f5316e2011-09-14 12:25:14 -040031
Timothy Warren24f325c2011-10-07 10:03:01 -040032class CI_DB_pdo_driver extends CI_DB {
33
34 var $dbdriver = 'pdo';
35
36 // the character used to excape - not necessary for PDO
37 var $_escape_char = '';
38 var $_like_escape_str;
39 var $_like_escape_chr;
Timothy Warren9f5316e2011-09-14 12:25:14 -040040
Timothy Warren24f325c2011-10-07 10:03:01 -040041
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 */
47 var $_count_string = "SELECT COUNT(*) AS ";
48 var $_random_keyword;
Timothy Warren530becb2011-10-25 10:37:31 -040049
50 var $options = array();
Timothy Warren24f325c2011-10-07 10:03:01 -040051
52 function __construct($params)
53 {
54 parent::__construct($params);
Timothy Warren9f5316e2011-09-14 12:25:14 -040055
Timothy Warren24f325c2011-10-07 10:03:01 -040056 // clause and character used for LIKE escape sequences
57 if (strpos($this->hostname, 'mysql') !== FALSE)
58 {
59 $this->_like_escape_str = '';
60 $this->_like_escape_chr = '';
Timothy Warren530becb2011-10-25 10:37:31 -040061
62 //Set the charset with the connection options
63 $this->options['PDO::MYSQL_ATTR_INIT_COMMAND'] = "SET NAMES {$this->char_set}";
Timothy Warren24f325c2011-10-07 10:03:01 -040064 }
65 else if (strpos($this->hostname, 'odbc') !== FALSE)
66 {
67 $this->_like_escape_str = " {escape '%s'} ";
68 $this->_like_escape_chr = '!';
69 }
70 else
71 {
72 $this->_like_escape_str = " ESCAPE '%s' ";
73 $this->_like_escape_chr = '!';
74 }
Timothy Warren9f5316e2011-09-14 12:25:14 -040075
Timothy Warren24f325c2011-10-07 10:03:01 -040076 $this->hostname = $this->hostname . ";dbname=".$this->database;
77 $this->trans_enabled = FALSE;
78
79 $this->_random_keyword = ' RND('.time().')'; // database specific random keyword
80 }
81
82 /**
83 * Non-persistent database connection
84 *
85 * @access private called by the base class
86 * @return resource
87 */
88 function db_connect()
89 {
Timothy Warren530becb2011-10-25 10:37:31 -040090 $this->options['PDO::ATTR_ERRMODE'] = PDO::ERRMODE_SILENT;
91 return new PDO($this->hostname,$this->username,$this->password, $this->options);
Timothy Warren24f325c2011-10-07 10:03:01 -040092 }
93
94 // --------------------------------------------------------------------
95
96 /**
97 * Persistent database connection
98 *
99 * @access private called by the base class
100 * @return resource
101 */
102 function db_pconnect()
103 {
104 return new PDO($this->hostname,$this->username,$this->password, array(
105 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
106 PDO::ATTR_PERSISTENT => true
107 ));
108 }
109
110 // --------------------------------------------------------------------
111
112 /**
113 * Reconnect
114 *
115 * Keep / reestablish the db connection if no queries have been
116 * sent for a length of time exceeding the server's idle timeout
117 *
118 * @access public
119 * @return void
120 */
121 function reconnect()
122 {
123 if ($this->db->db_debug)
124 {
125 return $this->db->display_error('db_unsuported_feature');
126 }
127 return FALSE;
128 }
129
130 // --------------------------------------------------------------------
131
132 /**
133 * Select the database
134 *
135 * @access private called by the base class
136 * @return resource
137 */
138 function db_select()
139 {
140 // Not needed for PDO
141 return TRUE;
142 }
143
144 // --------------------------------------------------------------------
145
146 /**
147 * Set client character set
148 *
149 * @access public
150 * @param string
151 * @param string
152 * @return resource
153 */
154 function db_set_charset($charset, $collation)
155 {
156 // @todo - add support if needed
157 return TRUE;
158 }
159
160 // --------------------------------------------------------------------
161
162 /**
163 * Version number query string
164 *
165 * @access public
166 * @return string
167 */
168 function _version()
169 {
170 return $this->conn_id->getAttribute(PDO::ATTR_CLIENT_VERSION);
171 }
172
173 // --------------------------------------------------------------------
174
175 /**
176 * Execute the query
177 *
178 * @access private called by the base class
179 * @param string an SQL query
180 * @return object
181 */
182 function _execute($sql)
183 {
184 $sql = $this->_prep_query($sql);
185 $result_id = $this->conn_id->query($sql);
Timothy Warren9f5316e2011-09-14 12:25:14 -0400186
Timothy Warren24f325c2011-10-07 10:03:01 -0400187 if (is_object($result_id))
188 {
189 $this->affect_rows = $result_id->rowCount();
190 }
191 else
192 {
193 $this->affect_rows = 0;
194 }
Timothy Warren9f5316e2011-09-14 12:25:14 -0400195
Timothy Warren24f325c2011-10-07 10:03:01 -0400196 return $result_id;
197 }
198
199 // --------------------------------------------------------------------
200
201 /**
202 * Prep the query
203 *
204 * If needed, each database adapter can prep the query string
205 *
206 * @access private called by execute()
207 * @param string an SQL query
208 * @return string
209 */
210 function _prep_query($sql)
211 {
212 return $sql;
213 }
214
215 // --------------------------------------------------------------------
216
217 /**
218 * Begin Transaction
219 *
220 * @access public
221 * @return bool
222 */
223 function trans_begin($test_mode = FALSE)
224 {
225 if ( ! $this->trans_enabled)
226 {
227 return TRUE;
228 }
229
230 // When transactions are nested we only begin/commit/rollback the outermost ones
231 if ($this->_trans_depth > 0)
232 {
233 return TRUE;
234 }
235
236 // Reset the transaction failure flag.
237 // If the $test_mode flag is set to TRUE transactions will be rolled back
238 // even if the queries produce a successful result.
239 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
240
241 return $this->conn_id->beginTransaction();
242 }
243
244 // --------------------------------------------------------------------
245
246 /**
247 * Commit Transaction
248 *
249 * @access public
250 * @return bool
251 */
252 function trans_commit()
253 {
254 if ( ! $this->trans_enabled)
255 {
256 return TRUE;
257 }
258
259 // When transactions are nested we only begin/commit/rollback the outermost ones
260 if ($this->_trans_depth > 0)
261 {
262 return TRUE;
263 }
264
265 $ret = $this->conn->commit();
266 return $ret;
267 }
268
269 // --------------------------------------------------------------------
270
271 /**
272 * Rollback Transaction
273 *
274 * @access public
275 * @return bool
276 */
277 function trans_rollback()
278 {
279 if ( ! $this->trans_enabled)
280 {
281 return TRUE;
282 }
283
284 // When transactions are nested we only begin/commit/rollback the outermost ones
285 if ($this->_trans_depth > 0)
286 {
287 return TRUE;
288 }
289
290 $ret = $this->conn_id->rollBack();
291 return $ret;
292 }
293
294 // --------------------------------------------------------------------
295
296 /**
297 * Escape String
298 *
299 * @access public
300 * @param string
301 * @param bool whether or not the string will be used in a LIKE condition
302 * @return string
303 */
304 function escape_str($str, $like = FALSE)
305 {
306 if (is_array($str))
307 {
308 foreach ($str as $key => $val)
309 {
310 $str[$key] = $this->escape_str($val, $like);
311 }
312
313 return $str;
314 }
Timothy Warren9f5316e2011-09-14 12:25:14 -0400315
Timothy Warren24f325c2011-10-07 10:03:01 -0400316 //Escape the string
317 $str = $this->conn_id->quote($str);
Timothy Warren9f5316e2011-09-14 12:25:14 -0400318
Timothy Warren24f325c2011-10-07 10:03:01 -0400319 //If there are duplicated quotes, trim them away
320 if (strpos($str, "'") === 0)
321 {
322 $str = substr($str, 1, -1);
323 }
Timothy Warren9f5316e2011-09-14 12:25:14 -0400324
Timothy Warren24f325c2011-10-07 10:03:01 -0400325 // escape LIKE condition wildcards
326 if ($like === TRUE)
327 {
328 $str = str_replace( array('%', '_', $this->_like_escape_chr),
329 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
330 $str);
331 }
332
333 return $str;
334 }
335
336 // --------------------------------------------------------------------
337
338 /**
339 * Affected Rows
340 *
341 * @access public
342 * @return integer
343 */
344 function affected_rows()
345 {
346 return $this->affect_rows;
347 }
348
349 // --------------------------------------------------------------------
350
351 /**
352 * Insert ID
353 *
354 * @access public
355 * @return integer
356 */
357 function insert_id($name=NULL)
358 {
359 //Convenience method for postgres insertid
360 if (strpos($this->hostname, 'pgsql') !== FALSE)
361 {
362 $v = $this->_version();
363
364 $table = func_num_args() > 0 ? func_get_arg(0) : NULL;
365
366 if ($table == NULL && $v >= '8.1')
367 {
368 $sql='SELECT LASTVAL() as ins_id';
369 }
370 $query = $this->query($sql);
371 $row = $query->row();
372 return $row->ins_id;
373 }
374 else
375 {
376 return $this->conn_id->lastInsertId($name);
377 }
378 }
379
380 // --------------------------------------------------------------------
381
382 /**
383 * "Count All" query
384 *
385 * Generates a platform-specific query string that counts all records in
386 * the specified database
387 *
388 * @access public
389 * @param string
390 * @return string
391 */
392 function count_all($table = '')
393 {
394 if ($table == '')
395 {
396 return 0;
397 }
398
399 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
400
401 if ($query->num_rows() == 0)
402 {
403 return 0;
404 }
405
406 $row = $query->row();
407 $this->_reset_select();
408 return (int) $row->numrows;
409 }
410
411 // --------------------------------------------------------------------
412
413 /**
414 * Show table query
415 *
416 * Generates a platform-specific query string so that the table names can be fetched
417 *
418 * @access private
419 * @param boolean
420 * @return string
421 */
422 function _list_tables($prefix_limit = FALSE)
423 {
424 $sql = "SHOW TABLES FROM `".$this->database."`";
425
426 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
427 {
428 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
429 return FALSE; // not currently supported
430 }
431
432 return $sql;
433 }
434
435 // --------------------------------------------------------------------
436
437 /**
438 * Show column query
439 *
440 * Generates a platform-specific query string so that the column names can be fetched
441 *
442 * @access public
443 * @param string the table name
444 * @return string
445 */
446 function _list_columns($table = '')
447 {
448 return "SHOW COLUMNS FROM ".$table;
449 }
450
451 // --------------------------------------------------------------------
452
453 /**
454 * Field data query
455 *
456 * Generates a platform-specific query so that the column data can be retrieved
457 *
458 * @access public
459 * @param string the table name
460 * @return object
461 */
462 function _field_data($table)
463 {
464 return "SELECT TOP 1 FROM ".$table;
465 }
466
467 // --------------------------------------------------------------------
468
469 /**
470 * The error message string
471 *
472 * @access private
473 * @return string
474 */
475 function _error_message()
476 {
477 $error_array = $this->conn_id->errorInfo();
478 return $error_array[2];
479 }
480
481 // --------------------------------------------------------------------
482
483 /**
484 * The error message number
485 *
486 * @access private
487 * @return integer
488 */
489 function _error_number()
490 {
491 return $this->conn_id->errorCode();
492 }
493
494 // --------------------------------------------------------------------
495
496 /**
497 * Escape the SQL Identifiers
498 *
499 * This function escapes column and table names
500 *
501 * @access private
502 * @param string
503 * @return string
504 */
505 function _escape_identifiers($item)
506 {
507 if ($this->_escape_char == '')
508 {
509 return $item;
510 }
511
512 foreach ($this->_reserved_identifiers as $id)
513 {
514 if (strpos($item, '.'.$id) !== FALSE)
515 {
516 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
517
518 // remove duplicates if the user already included the escape
519 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
520 }
521 }
522
523 if (strpos($item, '.') !== FALSE)
524 {
525 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
Timothy Warren9f5316e2011-09-14 12:25:14 -0400526
Timothy Warren24f325c2011-10-07 10:03:01 -0400527 }
528 else
529 {
530 $str = $this->_escape_char.$item.$this->_escape_char;
531 }
532
533 // remove duplicates if the user already included the escape
534 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
535 }
536
537 // --------------------------------------------------------------------
538
539 /**
540 * From Tables
541 *
542 * This function implicitly groups FROM tables so there is no confusion
543 * about operator precedence in harmony with SQL standards
544 *
545 * @access public
546 * @param type
547 * @return type
548 */
549 function _from_tables($tables)
550 {
551 if ( ! is_array($tables))
552 {
553 $tables = array($tables);
554 }
555
556 return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')';
557 }
558
559 // --------------------------------------------------------------------
560
561 /**
562 * Insert statement
563 *
564 * Generates a platform-specific insert string from the supplied data
565 *
566 * @access public
567 * @param string the table name
568 * @param array the insert keys
569 * @param array the insert values
570 * @return string
571 */
572 function _insert($table, $keys, $values)
573 {
574 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
575 }
Timothy Warren9f5316e2011-09-14 12:25:14 -0400576
Timothy Warren24f325c2011-10-07 10:03:01 -0400577 // --------------------------------------------------------------------
578
579 /**
580 * Insert_batch statement
581 *
582 * Generates a platform-specific insert string from the supplied data
583 *
584 * @access public
585 * @param string the table name
586 * @param array the insert keys
587 * @param array the insert values
588 * @return string
589 */
590 function _insert_batch($table, $keys, $values)
591 {
592 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
593 }
594
595 // --------------------------------------------------------------------
596
597 /**
598 * Update statement
599 *
600 * Generates a platform-specific update string from the supplied data
601 *
602 * @access public
603 * @param string the table name
604 * @param array the update data
605 * @param array the where clause
606 * @param array the orderby clause
607 * @param array the limit clause
608 * @return string
609 */
610 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
611 {
612 foreach ($values as $key => $val)
613 {
614 $valstr[] = $key." = ".$val;
615 }
616
617 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
618
619 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
620
621 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
622
623 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
624
625 $sql .= $orderby.$limit;
626
627 return $sql;
628 }
Timothy Warren9f5316e2011-09-14 12:25:14 -0400629
Timothy Warren24f325c2011-10-07 10:03:01 -0400630 // --------------------------------------------------------------------
631
632 /**
633 * Update_Batch statement
634 *
635 * Generates a platform-specific batch update string from the supplied data
636 *
637 * @access public
638 * @param string the table name
639 * @param array the update data
640 * @param array the where clause
641 * @return string
642 */
643 function _update_batch($table, $values, $index, $where = NULL)
644 {
645 $ids = array();
646 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
647
648 foreach ($values as $key => $val)
649 {
650 $ids[] = $val[$index];
651
652 foreach (array_keys($val) as $field)
653 {
654 if ($field != $index)
655 {
656 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
657 }
658 }
659 }
660
661 $sql = "UPDATE ".$table." SET ";
662 $cases = '';
663
664 foreach ($final as $k => $v)
665 {
666 $cases .= $k.' = CASE '."\n";
667 foreach ($v as $row)
668 {
669 $cases .= $row."\n";
670 }
671
672 $cases .= 'ELSE '.$k.' END, ';
673 }
674
675 $sql .= substr($cases, 0, -2);
676
677 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
678
679 return $sql;
680 }
681
682
683 // --------------------------------------------------------------------
684
685 /**
686 * Truncate statement
687 *
688 * Generates a platform-specific truncate string from the supplied data
689 * If the database does not support the truncate() command
690 * This function maps to "DELETE FROM table"
691 *
692 * @access public
693 * @param string the table name
694 * @return string
695 */
696 function _truncate($table)
697 {
698 return $this->_delete($table);
699 }
700
701 // --------------------------------------------------------------------
702
703 /**
704 * Delete statement
705 *
706 * Generates a platform-specific delete string from the supplied data
707 *
708 * @access public
709 * @param string the table name
710 * @param array the where clause
711 * @param string the limit clause
712 * @return string
713 */
714 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
715 {
716 $conditions = '';
717
718 if (count($where) > 0 OR count($like) > 0)
719 {
720 $conditions = "\nWHERE ";
721 $conditions .= implode("\n", $this->ar_where);
722
723 if (count($where) > 0 && count($like) > 0)
724 {
725 $conditions .= " AND ";
726 }
727 $conditions .= implode("\n", $like);
728 }
729
730 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
731
732 return "DELETE FROM ".$table.$conditions.$limit;
733 }
734
735 // --------------------------------------------------------------------
736
737 /**
738 * Limit string
739 *
740 * Generates a platform-specific LIMIT clause
741 *
742 * @access public
743 * @param string the sql query string
744 * @param integer the number of rows to limit the query to
745 * @param integer the offset value
746 * @return string
747 */
748 function _limit($sql, $limit, $offset)
749 {
750 if (strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE)
751 {
752 if ($offset == 0)
753 {
754 $offset = '';
755 }
756 else
757 {
758 $offset .= ", ";
759 }
760
761 return $sql."LIMIT ".$offset.$limit;
762 }
763 else
764 {
765 $sql .= "LIMIT ".$limit;
766
767 if ($offset > 0)
768 {
769 $sql .= " OFFSET ".$offset;
770 }
Timothy Warren9f5316e2011-09-14 12:25:14 -0400771
Timothy Warren24f325c2011-10-07 10:03:01 -0400772 return $sql;
773 }
774 }
775
776 // --------------------------------------------------------------------
777
778 /**
779 * Close DB Connection
780 *
781 * @access public
782 * @param resource
783 * @return void
784 */
785 function _close($conn_id)
786 {
787 $this->conn_id = null;
788 }
789
790
791}
792
793
794
795/* End of file pdo_driver.php */
796/* Location: ./system/database/drivers/pdo/pdo_driver.php */