blob: 19e069b06a13d72f411bf5fc4a57febc36a368c4 [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 */
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 = '';
37 var $_like_escape_str;
38 var $_like_escape_chr;
39
40
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
50 function __construct($params)
51 {
52 parent::__construct($params);
53
54 // 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
71 $this->hostname = $this->hostname . ";dbname=".$this->database;
72 $this->trans_enabled = FALSE;
73
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 {
85 return new PDO($this->hostname,$this->username,$this->password, array(
86 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
87 ));
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 {
100 return new PDO($this->hostname,$this->username,$this->password, array(
101 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
102 PDO::ATTR_PERSISTENT => true
103 ));
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 {
119 if ($this->db->db_debug)
120 {
121 return $this->db->display_error('db_unsuported_feature');
122 }
123 return FALSE;
124 }
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 {
166 return $this->conn_id->getAttribute(PDO::ATTR_CLIENT_VERSION);
167 }
168
169 // --------------------------------------------------------------------
170
171 /**
172 * Execute the query
173 *
174 * @access private called by the base class
175 * @param string an SQL query
176 * @return object
177 */
178 function _execute($sql)
179 {
180 $sql = $this->_prep_query($sql);
181 $result_id = $this->conn_id->query($sql);
182
183 if (is_object($result_id))
184 {
185 $this->affect_rows = $result_id->rowCount();
186 }
187 else
188 {
189 $this->affect_rows = 0;
190 }
191
192 return $result_id;
193 }
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
237 return $this->conn_id->beginTransaction();
238 }
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
261 $ret = $this->conn->commit();
262 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
286 $ret = $this->conn_id->rollBack();
287 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 }
311
312 //Escape the string
313 $str = $this->conn_id->quote($str);
314
315 //If there are duplicated quotes, trim them away
316 if (strpos($str, "'") === 0)
317 {
318 $str = substr($str, 1, -1);
319 }
320
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 {
342 return $this->affect_rows;
343 }
344
345 // --------------------------------------------------------------------
346
347 /**
348 * Insert ID
349 *
350 * @access public
351 * @return integer
352 */
353 function insert_id($name=NULL)
354 {
355 //Convenience method for postgres insertid
356 if (strpos($this->hostname, 'pgsql') !== FALSE)
357 {
358 $v = $this->_version();
359
360 $table = func_num_args() > 0 ? func_get_arg(0) : NULL;
361
362 if ($table == NULL && $v >= '8.1')
363 {
364 $sql='SELECT LASTVAL() as ins_id';
365 }
366 $query = $this->query($sql);
367 $row = $query->row();
368 return $row->ins_id;
369 }
370 else
371 {
372 return $this->conn_id->lastInsertId($name);
373 }
374 }
375
376 // --------------------------------------------------------------------
377
378 /**
379 * "Count All" query
380 *
381 * Generates a platform-specific query string that counts all records in
382 * the specified database
383 *
384 * @access public
385 * @param string
386 * @return string
387 */
388 function count_all($table = '')
389 {
390 if ($table == '')
391 {
392 return 0;
393 }
394
395 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
396
397 if ($query->num_rows() == 0)
398 {
399 return 0;
400 }
401
402 $row = $query->row();
403 $this->_reset_select();
404 return (int) $row->numrows;
405 }
406
407 // --------------------------------------------------------------------
408
409 /**
410 * Show table query
411 *
412 * Generates a platform-specific query string so that the table names can be fetched
413 *
414 * @access private
415 * @param boolean
416 * @return string
417 */
418 function _list_tables($prefix_limit = FALSE)
419 {
420 $sql = "SHOW TABLES FROM `".$this->database."`";
421
422 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
423 {
424 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
425 return FALSE; // not currently supported
426 }
427
428 return $sql;
429 }
430
431 // --------------------------------------------------------------------
432
433 /**
434 * Show column query
435 *
436 * Generates a platform-specific query string so that the column names can be fetched
437 *
438 * @access public
439 * @param string the table name
440 * @return string
441 */
442 function _list_columns($table = '')
443 {
444 return "SHOW COLUMNS FROM ".$table;
445 }
446
447 // --------------------------------------------------------------------
448
449 /**
450 * Field data query
451 *
452 * Generates a platform-specific query so that the column data can be retrieved
453 *
454 * @access public
455 * @param string the table name
456 * @return object
457 */
458 function _field_data($table)
459 {
460 return "SELECT TOP 1 FROM ".$table;
461 }
462
463 // --------------------------------------------------------------------
464
465 /**
466 * The error message string
467 *
468 * @access private
469 * @return string
470 */
471 function _error_message()
472 {
473 $error_array = $this->conn_id->errorInfo();
474 return $error_array[2];
475 }
476
477 // --------------------------------------------------------------------
478
479 /**
480 * The error message number
481 *
482 * @access private
483 * @return integer
484 */
485 function _error_number()
486 {
487 return $this->conn_id->errorCode();
488 }
489
490 // --------------------------------------------------------------------
491
492 /**
493 * Escape the SQL Identifiers
494 *
495 * This function escapes column and table names
496 *
497 * @access private
498 * @param string
499 * @return string
500 */
501 function _escape_identifiers($item)
502 {
503 if ($this->_escape_char == '')
504 {
505 return $item;
506 }
507
508 foreach ($this->_reserved_identifiers as $id)
509 {
510 if (strpos($item, '.'.$id) !== FALSE)
511 {
512 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
513
514 // remove duplicates if the user already included the escape
515 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
516 }
517 }
518
519 if (strpos($item, '.') !== FALSE)
520 {
521 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
522
523 }
524 else
525 {
526 $str = $this->_escape_char.$item.$this->_escape_char;
527 }
528
529 // remove duplicates if the user already included the escape
530 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
531 }
532
533 // --------------------------------------------------------------------
534
535 /**
536 * From Tables
537 *
538 * This function implicitly groups FROM tables so there is no confusion
539 * about operator precedence in harmony with SQL standards
540 *
541 * @access public
542 * @param type
543 * @return type
544 */
545 function _from_tables($tables)
546 {
547 if ( ! is_array($tables))
548 {
549 $tables = array($tables);
550 }
551
552 return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')';
553 }
554
555 // --------------------------------------------------------------------
556
557 /**
558 * Insert statement
559 *
560 * Generates a platform-specific insert string from the supplied data
561 *
562 * @access public
563 * @param string the table name
564 * @param array the insert keys
565 * @param array the insert values
566 * @return string
567 */
568 function _insert($table, $keys, $values)
569 {
570 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
571 }
572
573 // --------------------------------------------------------------------
574
575 /**
576 * Insert_batch statement
577 *
578 * Generates a platform-specific insert string from the supplied data
579 *
580 * @access public
581 * @param string the table name
582 * @param array the insert keys
583 * @param array the insert values
584 * @return string
585 */
586 function _insert_batch($table, $keys, $values)
587 {
588 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
589 }
590
591 // --------------------------------------------------------------------
592
593 /**
594 * Update statement
595 *
596 * Generates a platform-specific update string from the supplied data
597 *
598 * @access public
599 * @param string the table name
600 * @param array the update data
601 * @param array the where clause
602 * @param array the orderby clause
603 * @param array the limit clause
604 * @return string
605 */
606 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
607 {
608 foreach ($values as $key => $val)
609 {
610 $valstr[] = $key." = ".$val;
611 }
612
613 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
614
615 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
616
617 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
618
619 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
620
621 $sql .= $orderby.$limit;
622
623 return $sql;
624 }
625
626 // --------------------------------------------------------------------
627
628 /**
629 * Update_Batch statement
630 *
631 * Generates a platform-specific batch update string from the supplied data
632 *
633 * @access public
634 * @param string the table name
635 * @param array the update data
636 * @param array the where clause
637 * @return string
638 */
639 function _update_batch($table, $values, $index, $where = NULL)
640 {
641 $ids = array();
642 $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
643
644 foreach ($values as $key => $val)
645 {
646 $ids[] = $val[$index];
647
648 foreach (array_keys($val) as $field)
649 {
650 if ($field != $index)
651 {
652 $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
653 }
654 }
655 }
656
657 $sql = "UPDATE ".$table." SET ";
658 $cases = '';
659
660 foreach ($final as $k => $v)
661 {
662 $cases .= $k.' = CASE '."\n";
663 foreach ($v as $row)
664 {
665 $cases .= $row."\n";
666 }
667
668 $cases .= 'ELSE '.$k.' END, ';
669 }
670
671 $sql .= substr($cases, 0, -2);
672
673 $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
674
675 return $sql;
676 }
677
678
679 // --------------------------------------------------------------------
680
681 /**
682 * Truncate statement
683 *
684 * Generates a platform-specific truncate string from the supplied data
685 * If the database does not support the truncate() command
686 * This function maps to "DELETE FROM table"
687 *
688 * @access public
689 * @param string the table name
690 * @return string
691 */
692 function _truncate($table)
693 {
694 return $this->_delete($table);
695 }
696
697 // --------------------------------------------------------------------
698
699 /**
700 * Delete statement
701 *
702 * Generates a platform-specific delete string from the supplied data
703 *
704 * @access public
705 * @param string the table name
706 * @param array the where clause
707 * @param string the limit clause
708 * @return string
709 */
710 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
711 {
712 $conditions = '';
713
714 if (count($where) > 0 OR count($like) > 0)
715 {
716 $conditions = "\nWHERE ";
717 $conditions .= implode("\n", $this->ar_where);
718
719 if (count($where) > 0 && count($like) > 0)
720 {
721 $conditions .= " AND ";
722 }
723 $conditions .= implode("\n", $like);
724 }
725
726 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
727
728 return "DELETE FROM ".$table.$conditions.$limit;
729 }
730
731 // --------------------------------------------------------------------
732
733 /**
734 * Limit string
735 *
736 * Generates a platform-specific LIMIT clause
737 *
738 * @access public
739 * @param string the sql query string
740 * @param integer the number of rows to limit the query to
741 * @param integer the offset value
742 * @return string
743 */
744 function _limit($sql, $limit, $offset)
745 {
746 if (strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE)
747 {
748 if ($offset == 0)
749 {
750 $offset = '';
751 }
752 else
753 {
754 $offset .= ", ";
755 }
756
757 return $sql."LIMIT ".$offset.$limit;
758 }
759 else
760 {
761 $sql .= "LIMIT ".$limit;
762
763 if ($offset > 0)
764 {
765 $sql .= " OFFSET ".$offset;
766 }
767
768 return $sql;
769 }
770 }
771
772 // --------------------------------------------------------------------
773
774 /**
775 * Close DB Connection
776 *
777 * @access public
778 * @param resource
779 * @return void
780 */
781 function _close($conn_id)
782 {
783 $this->conn_id = null;
784 }
785
786
787}
788
789
790
791/* End of file pdo_driver.php */
792/* Location: ./system/database/drivers/pdo/pdo_driver.php */