1 <?php defined('SYSPATH') OR die('No direct access allowed.');
3 * PostgreSQL 8.1+ Database Driver
5 * $Id: Pgsql.php 4344 2009-05-11 16:41:39Z zombor $
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 class Database_Pgsql_Driver extends Database_Driver {
14 // Database connection link
19 * Sets the config for the class.
21 * @param array database configuration
23 public function __construct($config)
25 $this->db_config = $config;
27 Kohana::log('debug', 'PgSQL Database Driver Initialized');
30 public function connect()
32 // Check if link already exists
33 if (is_resource($this->link))
36 // Import the connect variables
37 extract($this->db_config['connection']);
39 // Persistent connections enabled?
40 $connect = ($this->db_config['persistent'] == TRUE) ? 'pg_pconnect' : 'pg_connect';
42 // Build the connection info
43 $port = isset($port) ? 'port=\''.$port.'\'' : '';
44 $host = isset($host) ? 'host=\''.$host.'\' '.$port : ''; // if no host, connect with the socket
46 $connection_string = $host.' dbname=\''.$database.'\' user=\''.$user.'\' password=\''.$pass.'\'';
47 // Make the connection and select the database
48 if ($this->link = $connect($connection_string))
50 if ($charset = $this->db_config['character_set'])
52 echo $this->set_charset($charset);
55 // Clear password after successful connect
56 $this->db_config['connection']['pass'] = NULL;
64 public function query($sql)
66 // Only cache if it's turned on, and only cache if it's not a write statement
67 if ($this->db_config['cache'] AND ! preg_match('#\b(?:INSERT|UPDATE|SET)\b#i', $sql))
69 $hash = $this->query_hash($sql);
71 if ( ! isset($this->query_cache[$hash]))
73 // Set the cached object
74 $this->query_cache[$hash] = new Pgsql_Result(pg_query($this->link, $sql), $this->link, $this->db_config['object'], $sql);
78 // Rewind cached result
79 $this->query_cache[$hash]->rewind();
82 return $this->query_cache[$hash];
85 // Suppress warning triggered when a database error occurs (e.g., a constraint violation)
86 return new Pgsql_Result(@pg_query($this->link, $sql), $this->link, $this->db_config['object'], $sql);
89 public function set_charset($charset)
91 $this->query('SET client_encoding TO '.pg_escape_string($this->link, $charset));
94 public function escape_table($table)
96 if (!$this->db_config['escape'])
99 return '"'.str_replace('.', '"."', $table).'"';
102 public function escape_column($column)
104 if (!$this->db_config['escape'])
110 // This matches any functions we support to SELECT.
111 if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches))
113 if ( count($matches) == 3)
115 return $matches[1].'('.$this->escape_column($matches[2]).')';
117 else if ( count($matches) == 5)
119 return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]);
123 // This matches any modifiers we support to SELECT.
124 if ( ! preg_match('/\b(?:all|distinct)\s/i', $column))
126 if (stripos($column, ' AS ') !== FALSE)
128 // Force 'AS' to uppercase
129 $column = str_ireplace(' AS ', ' AS ', $column);
131 // Runs escape_column on both sides of an AS statement
132 $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column));
134 // Re-create the AS statement
135 return implode(' AS ', $column);
138 return preg_replace('/[^.*]+/', '"$0"', $column);
141 $parts = explode(' ', $column);
144 for ($i = 0, $c = count($parts); $i < $c; $i++)
146 // The column is always last
149 $column .= preg_replace('/[^.*]+/', '"$0"', $parts[$i]);
151 else // otherwise, it's a modifier
153 $column .= $parts[$i].' ';
159 public function regex($field, $match, $type, $num_regexs)
161 $prefix = ($num_regexs == 0) ? '' : $type;
163 return $prefix.' '.$this->escape_column($field).' ~* \''.$this->escape_str($match).'\'';
166 public function notregex($field, $match, $type, $num_regexs)
168 $prefix = $num_regexs == 0 ? '' : $type;
170 return $prefix.' '.$this->escape_column($field).' !~* \''.$this->escape_str($match) . '\'';
173 public function limit($limit, $offset = 0)
175 return 'LIMIT '.$limit.' OFFSET '.$offset;
178 public function compile_select($database)
180 $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT ';
181 $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*';
183 if (count($database['from']) > 0)
186 $sql .= implode(', ', $database['from']);
189 if (count($database['join']) > 0)
191 foreach($database['join'] AS $join)
193 $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions'];
197 if (count($database['where']) > 0)
202 $sql .= implode("\n", $database['where']);
204 if (count($database['groupby']) > 0)
206 $sql .= "\nGROUP BY ";
207 $sql .= implode(', ', $database['groupby']);
210 if (count($database['having']) > 0)
213 $sql .= implode("\n", $database['having']);
216 if (count($database['orderby']) > 0)
218 $sql .= "\nORDER BY ";
219 $sql .= implode(', ', $database['orderby']);
222 if (is_numeric($database['limit']))
225 $sql .= $this->limit($database['limit'], $database['offset']);
231 public function escape_str($str)
233 if (!$this->db_config['escape'])
236 is_resource($this->link) or $this->connect();
238 return pg_escape_string($this->link, $str);
241 public function list_tables()
243 $sql = 'SELECT table_schema || \'.\' || table_name FROM information_schema.tables WHERE table_schema NOT IN (\'pg_catalog\', \'information_schema\')';
244 $result = $this->query($sql)->result(FALSE, PGSQL_ASSOC);
247 foreach ($result as $row)
249 $retval[] = current($row);
255 public function show_error()
257 return pg_last_error($this->link);
260 public function list_fields($table)
264 foreach ($this->field_data($table) as $row)
266 // Make an associative array
267 $result[$row->column_name] = $this->sql_type($row->data_type);
269 if (!strncmp($row->column_default, 'nextval(', 8))
271 $result[$row->column_name]['sequenced'] = TRUE;
274 if ($row->is_nullable === 'YES')
276 $result[$row->column_name]['null'] = TRUE;
281 throw new Kohana_Database_Exception('database.table_not_found', $table);
286 public function field_data($table)
288 // http://www.postgresql.org/docs/8.3/static/infoschema-columns.html
289 $result = $this->query('
290 SELECT column_name, column_default, is_nullable, data_type, udt_name,
291 character_maximum_length, numeric_precision, numeric_precision_radix, numeric_scale
292 FROM information_schema.columns
293 WHERE table_name = \''. $this->escape_str($table) .'\'
294 ORDER BY ordinal_position
297 return $result->result_array(TRUE);
300 } // End Database_Pgsql_Driver Class
305 class Pgsql_Result extends Database_Result {
307 // Data fetching types
308 protected $fetch_type = 'pgsql_fetch_object';
309 protected $return_type = PGSQL_ASSOC;
312 * Sets up the result variables.
314 * @param resource query result
315 * @param resource database link
316 * @param boolean return objects or arrays
317 * @param string SQL query that was run
319 public function __construct($result, $link, $object = TRUE, $sql)
322 $this->result = $result;
324 // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query
325 if (is_resource($result))
327 // Its an DELETE, INSERT, REPLACE, or UPDATE query
328 if (preg_match('/^(?:delete|insert|replace|update)\b/iD', trim($sql), $matches))
330 $this->insert_id = (strtolower($matches[0]) == 'insert') ? $this->insert_id() : FALSE;
331 $this->total_rows = pg_affected_rows($this->result);
335 $this->current_row = 0;
336 $this->total_rows = pg_num_rows($this->result);
337 $this->fetch_type = ($object === TRUE) ? 'pg_fetch_object' : 'pg_fetch_array';
342 throw new Kohana_Database_Exception('database.error', pg_last_error().' - '.$sql);
346 $this->result($object);
353 * Magic __destruct function, frees the result.
355 public function __destruct()
357 if (is_resource($this->result))
359 pg_free_result($this->result);
363 public function result($object = TRUE, $type = PGSQL_ASSOC)
365 $this->fetch_type = ((bool) $object) ? 'pg_fetch_object' : 'pg_fetch_array';
367 // This check has to be outside the previous statement, because we do not
368 // know the state of fetch_type when $object = NULL
369 // NOTE - The class set by $type must be defined before fetching the result,
370 // autoloading is disabled to save a lot of stupid overhead.
371 if ($this->fetch_type == 'pg_fetch_object')
373 $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
377 $this->return_type = $type;
383 public function as_array($object = NULL, $type = PGSQL_ASSOC)
385 return $this->result_array($object, $type);
388 public function result_array($object = NULL, $type = PGSQL_ASSOC)
392 if (is_string($object))
396 elseif (is_bool($object))
398 if ($object === TRUE)
400 $fetch = 'pg_fetch_object';
402 // NOTE - The class set by $type must be defined before fetching the result,
403 // autoloading is disabled to save a lot of stupid overhead.
404 $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
408 $fetch = 'pg_fetch_array';
413 // Use the default config values
414 $fetch = $this->fetch_type;
416 if ($fetch == 'pg_fetch_object')
418 $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
422 if ($this->total_rows)
424 pg_result_seek($this->result, 0);
426 while ($row = $fetch($this->result, NULL, $type))
435 public function insert_id()
437 if ($this->insert_id === NULL)
439 $query = 'SELECT LASTVAL() AS insert_id';
441 // Disable error reporting for this, just to silence errors on
442 // tables that have no serial column.
443 $ER = error_reporting(0);
445 $result = pg_query($this->link, $query);
446 $insert_id = pg_fetch_array($result, NULL, PGSQL_ASSOC);
448 $this->insert_id = $insert_id['insert_id'];
450 // Reset error reporting
451 error_reporting($ER);
454 return $this->insert_id;
457 public function seek($offset)
459 if ($this->offsetExists($offset) AND pg_result_seek($this->result, $offset))
461 // Set the current row to the offset
462 $this->current_row = $offset;
470 public function list_fields()
472 $field_names = array();
474 $fields = pg_num_fields($this->result);
475 for ($i = 0; $i < $fields; ++$i)
477 $field_names[] = pg_field_name($this->result, $i);
484 * ArrayAccess: offsetGet
486 public function offsetGet($offset)
488 if ( ! $this->seek($offset))
491 // Return the row by calling the defined fetching callback
492 $fetch = $this->fetch_type;
493 return $fetch($this->result, NULL, $this->return_type);
496 } // End Pgsql_Result Class
499 * PostgreSQL Prepared Statement (experimental)
501 class Kohana_Pgsql_Statement {
503 protected $link = NULL;
506 public function __construct($sql, $link)
510 $this->stmt = $this->link->prepare($sql);
515 public function __destruct()
517 $this->stmt->close();
520 // Sets the bind parameters
521 public function bind_params()
523 $argv = func_get_args();
527 // sets the statement values to the bound parameters
528 public function set_vals()
533 // Runs the statement
534 public function execute()