1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
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
16 // ------------------------------------------------------------------------
19 * Postgre Database Adapter Class
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.
25 * @package CodeIgniter
28 * @author ExpressionEngine Dev Team
29 * @link http://codeigniter.com/user_guide/database/
31 class CI_DB_postgre_driver extends CI_DB {
33 var $dbdriver = 'postgre';
35 var $_escape_char = '"';
37 // clause and character used for LIKE escape sequences
38 var $_like_escape_str = " ESCAPE '%s' ";
39 var $_like_escape_chr = '!';
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.
46 var $_count_string = "SELECT COUNT(*) AS ";
47 var $_random_keyword = ' RANDOM()'; // database specific random keyword
55 function _connect_string()
60 'database' => 'dbname',
62 'password' => 'password'
66 foreach ($components as $key => $val)
68 if (isset($this->$key) && $this->$key != '')
70 $connect_string .= " $val=".$this->$key;
73 return trim($connect_string);
76 // --------------------------------------------------------------------
79 * Non-persistent database connection
81 * @access private called by the base class
86 return @pg_connect($this->_connect_string());
89 // --------------------------------------------------------------------
92 * Persistent database connection
94 * @access private called by the base class
97 function db_pconnect()
99 return @pg_pconnect($this->_connect_string());
102 // --------------------------------------------------------------------
107 * Keep / reestablish the db connection if no queries have been
108 * sent for a length of time exceeding the server's idle timeout
115 if (pg_ping($this->conn_id) === FALSE)
117 $this->conn_id = FALSE;
121 // --------------------------------------------------------------------
124 * Select the database
126 * @access private called by the base class
131 // Not needed for Postgre so we'll return TRUE
135 // --------------------------------------------------------------------
138 * Set client character set
145 function db_set_charset($charset, $collation)
147 // @todo - add support if needed
151 // --------------------------------------------------------------------
154 * Version number query string
161 return "SELECT version() AS ver";
164 // --------------------------------------------------------------------
169 * @access private called by the base class
170 * @param string an SQL query
173 function _execute($sql)
175 $sql = $this->_prep_query($sql);
176 return @pg_query($this->conn_id, $sql);
179 // --------------------------------------------------------------------
184 * If needed, each database adapter can prep the query string
186 * @access private called by execute()
187 * @param string an SQL query
190 function _prep_query($sql)
195 // --------------------------------------------------------------------
203 function trans_begin($test_mode = FALSE)
205 if ( ! $this->trans_enabled)
210 // When transactions are nested we only begin/commit/rollback the outermost ones
211 if ($this->_trans_depth > 0)
216 // Reset the transaction failure flag.
217 // If the $test_mode flag is set to TRUE transactions will be rolled back
218 // even if the queries produce a successful result.
219 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
221 return @pg_exec($this->conn_id, "begin");
224 // --------------------------------------------------------------------
232 function trans_commit()
234 if ( ! $this->trans_enabled)
239 // When transactions are nested we only begin/commit/rollback the outermost ones
240 if ($this->_trans_depth > 0)
245 return @pg_exec($this->conn_id, "commit");
248 // --------------------------------------------------------------------
251 * Rollback Transaction
256 function trans_rollback()
258 if ( ! $this->trans_enabled)
263 // When transactions are nested we only begin/commit/rollback the outermost ones
264 if ($this->_trans_depth > 0)
269 return @pg_exec($this->conn_id, "rollback");
272 // --------------------------------------------------------------------
279 * @param bool whether or not the string will be used in a LIKE condition
282 function escape_str($str, $like = FALSE)
286 foreach ($str as $key => $val)
288 $str[$key] = $this->escape_str($val, $like);
294 $str = pg_escape_string($str);
296 // escape LIKE condition wildcards
299 $str = str_replace( array('%', '_', $this->_like_escape_chr),
300 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
307 // --------------------------------------------------------------------
315 function affected_rows()
317 return @pg_affected_rows($this->result_id);
320 // --------------------------------------------------------------------
330 $v = $this->_version();
333 $table = func_num_args() > 0 ? func_get_arg(0) : NULL;
334 $column = func_num_args() > 1 ? func_get_arg(1) : NULL;
336 if ($table == NULL && $v >= '8.1')
338 $sql='SELECT LASTVAL() as ins_id';
340 elseif ($table != NULL && $column != NULL && $v >= '8.0')
342 $sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column);
343 $query = $this->query($sql);
344 $row = $query->row();
345 $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq);
347 elseif ($table != NULL)
349 // seq_name passed in table parameter
350 $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table);
354 return pg_last_oid($this->result_id);
356 $query = $this->query($sql);
357 $row = $query->row();
361 // --------------------------------------------------------------------
366 * Generates a platform-specific query string that counts all records in
367 * the specified database
373 function count_all($table = '')
380 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
382 if ($query->num_rows() == 0)
387 $row = $query->row();
388 return (int) $row->numrows;
391 // --------------------------------------------------------------------
396 * Generates a platform-specific query string so that the table names can be fetched
402 function _list_tables($prefix_limit = FALSE)
404 $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'";
406 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
408 $sql .= " AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
414 // --------------------------------------------------------------------
419 * Generates a platform-specific query string so that the column names can be fetched
422 * @param string the table name
425 function _list_columns($table = '')
427 return "SELECT column_name FROM information_schema.columns WHERE table_name ='".$table."'";
430 // --------------------------------------------------------------------
435 * Generates a platform-specific query so that the column data can be retrieved
438 * @param string the table name
441 function _field_data($table)
443 return "SELECT * FROM ".$table." LIMIT 1";
446 // --------------------------------------------------------------------
449 * The error message string
454 function _error_message()
456 return pg_last_error($this->conn_id);
459 // --------------------------------------------------------------------
462 * The error message number
467 function _error_number()
472 // --------------------------------------------------------------------
475 * Escape the SQL Identifiers
477 * This function escapes column and table names
483 function _escape_identifiers($item)
485 if ($this->_escape_char == '')
490 foreach ($this->_reserved_identifiers as $id)
492 if (strpos($item, '.'.$id) !== FALSE)
494 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
496 // remove duplicates if the user already included the escape
497 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
501 if (strpos($item, '.') !== FALSE)
503 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
507 $str = $this->_escape_char.$item.$this->_escape_char;
510 // remove duplicates if the user already included the escape
511 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
514 // --------------------------------------------------------------------
519 * This function implicitly groups FROM tables so there is no confusion
520 * about operator precedence in harmony with SQL standards
526 function _from_tables($tables)
528 if ( ! is_array($tables))
530 $tables = array($tables);
533 return implode(', ', $tables);
536 // --------------------------------------------------------------------
541 * Generates a platform-specific insert string from the supplied data
544 * @param string the table name
545 * @param array the insert keys
546 * @param array the insert values
549 function _insert($table, $keys, $values)
551 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
554 // --------------------------------------------------------------------
559 * Generates a platform-specific update string from the supplied data
562 * @param string the table name
563 * @param array the update data
564 * @param array the where clause
565 * @param array the orderby clause
566 * @param array the limit clause
569 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
571 foreach ($values as $key => $val)
573 $valstr[] = $key." = ".$val;
576 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
578 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
580 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
582 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
584 $sql .= $orderby.$limit;
589 // --------------------------------------------------------------------
594 * Generates a platform-specific truncate string from the supplied data
595 * If the database does not support the truncate() command
596 * This function maps to "DELETE FROM table"
599 * @param string the table name
602 function _truncate($table)
604 return "TRUNCATE ".$table;
607 // --------------------------------------------------------------------
612 * Generates a platform-specific delete string from the supplied data
615 * @param string the table name
616 * @param array the where clause
617 * @param string the limit clause
620 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
624 if (count($where) > 0 OR count($like) > 0)
626 $conditions = "\nWHERE ";
627 $conditions .= implode("\n", $this->ar_where);
629 if (count($where) > 0 && count($like) > 0)
631 $conditions .= " AND ";
633 $conditions .= implode("\n", $like);
636 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
638 return "DELETE FROM ".$table.$conditions.$limit;
641 // --------------------------------------------------------------------
645 * Generates a platform-specific LIMIT clause
648 * @param string the sql query string
649 * @param integer the number of rows to limit the query to
650 * @param integer the offset value
653 function _limit($sql, $limit, $offset)
655 $sql .= "LIMIT ".$limit;
659 $sql .= " OFFSET ".$offset;
665 // --------------------------------------------------------------------
668 * Close DB Connection
674 function _close($conn_id)
683 /* End of file postgre_driver.php */
684 /* Location: ./system/database/drivers/postgre/postgre_driver.php */