Source for file pgsql.php
Documentation is available at pgsql.php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Rui Hirokawa <hirokawa@php.net> |
// | Stig Bakken <ssb@php.net> |
// | Maintainer: Daniel Convissor <danielc@php.net> |
// +----------------------------------------------------------------------+
// $Id: pgsql.php,v 1.75 2004/04/07 05:12:28 danielc Exp $
require_once 'DB/common.php';
* Database independent query interface definition for PHP's PostgreSQL
* @version $Id: pgsql.php,v 1.75 2004/04/07 05:12:28 danielc Exp $
* @author Rui Hirokawa <hirokawa@php.net>
* @author Stig Bakken <ssb@php.net>
* Connect to a database and log in as the specified user.
* @param $dsn the data source name (see DB::parseDSN for syntax)
* @param $persistent (optional) whether the connection should
* @return int DB_OK on success, a DB error code on failure.
function connect($dsninfo, $persistent = false )
$protocol = $dsninfo['protocol'] ? $dsninfo['protocol'] : 'tcp';
if ($protocol == 'tcp') {
if ($dsninfo['hostspec']) {
$connstr .= 'host=' . $dsninfo['hostspec'];
$connstr .= ' port=' . $dsninfo['port'];
} elseif ($protocol == 'unix') {
// Allow for pg socket in non-standard locations.
if ($dsninfo['socket']) {
$connstr .= 'host=' . $dsninfo['socket'];
if ($dsninfo['database']) {
$connstr .= ' dbname=\'' . addslashes($dsninfo['database']) . '\'';
if ($dsninfo['username']) {
$connstr .= ' user=\'' . addslashes($dsninfo['username']) . '\'';
if ($dsninfo['password']) {
$connstr .= ' password=\'' . addslashes($dsninfo['password']) . '\'';
if (!empty ($dsninfo['options'])) {
$connstr .= ' options=' . $dsninfo['options'];
if (!empty ($dsninfo['tty'])) {
$connstr .= ' tty=' . $dsninfo['tty'];
$connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
$conn = $connect_function($connstr);
* Log out and disconnect from the database.
* @return bool true on success, false if not connected.
* Send a query to PostgreSQL and return the results as a
* PostgreSQL resource identifier.
* @param $query the SQL query
* @return int returns a valid PostgreSQL result for successful SELECT
* queries, DB_OK for other successful queries. A DB error code
* is returned on failure.
$query = $this->modifyQuery ($query);
// Determine which queries that should return data, and which
// should return an error code only.
$this->affected = @pg_cmdtuples ($result);
} elseif (preg_match('/^\s*\(?\s*(SELECT(?!\s+INTO)|EXPLAIN|SHOW)\s/si', $query)) {
ABORT, ALTER, BEGIN, CLOSE, CLUSTER, COMMIT, COPY,
CREATE, DECLARE, DELETE, DROP TABLE, EXPLAIN, FETCH,
GRANT, INSERT, LISTEN, LOAD, LOCK, MOVE, NOTIFY, RESET,
REVOKE, ROLLBACK, SELECT, SELECT INTO, SET, SHOW,
$this->row[(int) $result] = 0; // reset the row counter.
$numrows = $this->numrows ($result);
$this->num_rows[(int) $result] = $numrows;
* Move the internal pgsql result pointer to the next available result
* @param a valid fbsql result resource
* @return true if a result is available otherwise return false
* Determine PEAR::DB error code from the database's text error message.
* @param string $errormsg error message returned from the database
* @return integer an error number from a DB error constant
if (!isset ($error_regexps)) {
'/(([Rr]elation|[Ss]equence|[Tt]able)( [\"\'].*[\"\'])? does not exist|[Cc]lass ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
'/[Rr]elation [\"\'].*[\"\'] already exists|[Cc]annot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS,
'/ttribute [\"\'].*[\"\'] not found$|[Rr]elation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
foreach ($error_regexps as $regexp => $code) {
// Fall back to DB_ERROR if there was no mapping.
* Fetch a row and insert the data into an existing array.
* Formating of the array and the data therein are configurable.
* See DB_result::fetchInto() for more information.
* @param resource $result query result identifier
* @param array $arr (reference) array where data from the row
* @param int $fetchmode how the resulting array should be indexed
* @param int $rownum the row number to fetch
* @return mixed DB_OK on success, null when end of result set is
* @see DB_result::fetchInto()
function fetchInto ($result, &$arr, $fetchmode, $rownum=null )
$rownum = ($rownum !== null ) ? $rownum : $this->row[$result];
if ($rownum >= $this->num_rows[$result]) {
$arr = @pg_fetch_array ($result, $rownum, PGSQL_ASSOC );
$arr = @pg_fetch_row ($result, $rownum);
$this->_rtrimArrayValues ($arr);
$this->_convertNullArrayValuesToEmpty ($arr);
$this->row[$result] = ++ $rownum;
* Free the internal resources associated with $result.
* @param $result int PostgreSQL result identifier
* @return bool true on success, false if $result is invalid
unset ($this->row[(int) $result]);
return @pg_freeresult ($result);
* @deprecated Deprecated in release 1.6.0
* Format input so it can be safely used in a query
* @param mixed $in data to be quoted
* @return mixed Submitted variable's type = returned value:
* + null = the string <samp>NULL</samp>
* + boolean = string <samp>TRUE</samp> or <samp>FALSE</samp>
* + integer or double = the unquoted number
* + other (including strings and numeric strings) =
* the data escaped according to MySQL's settings
* then encapsulated between single quotes
return $in ? 'TRUE' : 'FALSE';
* Escape a string according to the current DBMS's standards
* PostgreSQL treats a backslash as an escape character, so they are
* Not using pg_escape_string() yet because it requires PostgreSQL
* to be at version 7.2 or greater.
* @param string $str the string to be escaped
* @return string the escaped string
* Get the number of columns in a result set.
* @param $result resource PostgreSQL result identifier
* @return int the number of columns per row in $result
$cols = @pg_numfields ($result);
* Get the number of rows in a result set.
* @param $result resource PostgreSQL result identifier
* @return int the number of rows in $result
$rows = @pg_numrows ($result);
* Get the native error code of the last error (if any) that
* occured on the current connection.
* @return int native PostgreSQL error code
* Enable/disable automatic commits
// XXX if $this->transaction_opcount > 0, we should probably
* Commit the current transaction.
// (disabled) hack to shut up error messages from libpq.a
//@fclose(@fopen("php://stderr", "w"));
* Roll back (undo) the current transaction.
* Gets the number of rows affected by the last query.
* if the last query was a select, returns 0.
* @return int number of rows affected by the last query or DB_ERROR
* Returns the next free id in a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true, the seqence is automatically
* created if it does not exist
* @return int the next id number in the sequence. DB_Error if problem.
* @see DB_common::nextID()
function nextId($seq_name, $ondemand = true )
$seqname = $this->getSequenceName ($seq_name);
$this->pushErrorHandling (PEAR_ERROR_RETURN );
$result = & $this->query(" SELECT NEXTVAL('${seqname}')" );
$this->popErrorHandling ();
$this->pushErrorHandling (PEAR_ERROR_RETURN );
$this->popErrorHandling ();
* @param string $seq_name the name of the sequence
* @return mixed DB_OK on success or DB error on error
$seqname = $this->getSequenceName ($seq_name);
$result = $this->query(" CREATE SEQUENCE ${seqname}" );
* @param string $seq_name the name of the sequence
* @return mixed DB_OK on success or DB error on error
$seqname = $this->getSequenceName ($seq_name);
return $this->query(" DROP SEQUENCE ${seqname}" );
// {{{ modifyLimitQuery()
$query = $query . " LIMIT $count OFFSET $from";
* Gather information about an error, then use that info to create a
* DB error object and finally return that object.
* @param integer $errno PEAR error number (usually a DB constant) if
* manually raising an error
* @return object DB error object
* @see DB_common::raiseError()
return $this->raiseError($err, null , null , null , $native);
* @param int $resource PostgreSQL result identifier
* @param int $num_field the field number
* @return string The flags of the field ("not_null", "default_value",
* "primary_key", "unique_key" and "multiple_key"
* are supported). The default value is passed
* through rawurlencode() in case there are spaces in it.
function _pgFieldFlags ($resource, $num_field, $table_name)
$field_name = @pg_fieldname ($resource, $num_field);
$result = @pg_exec ($this->connection, " SELECT f.attnotnull, f.atthasdef
FROM pg_attribute f, pg_class tab, pg_type typ
WHERE tab.relname = typ.typname
AND typ.typrelid = f.attrelid
AND f.attname = '$field_name'
AND tab.relname = '$table_name'" );
if (@pg_numrows ($result) > 0 ) {
$row = @pg_fetch_row ($result, 0 );
$flags = ($row[0 ] == 't') ? 'not_null ' : '';
$result = @pg_exec ($this->connection, " SELECT a.adsrc
FROM pg_attribute f, pg_class tab, pg_type typ, pg_attrdef a
WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
AND f.attrelid = a.adrelid AND f.attname = '$field_name'
AND tab.relname = '$table_name' AND f.attnum = a.adnum" );
$row = @pg_fetch_row ($result, 0 );
$result = @pg_exec ($this->connection, " SELECT i.indisunique, i.indisprimary, i.indkey
FROM pg_attribute f, pg_class tab, pg_type typ, pg_index i
WHERE tab.relname = typ.typname
AND typ.typrelid = f.attrelid
AND f.attrelid = i.indrelid
AND f.attname = '$field_name'
AND tab.relname = '$table_name'" );
$count = @pg_numrows ($result);
for ($i = 0; $i < $count ; $i++ ) {
$row = @pg_fetch_row ($result, $i);
$flags .= ($row[0 ] == 't' && $row[1 ] == 'f') ? 'unique_key ' : '';
$flags .= ($row[1 ] == 't') ? 'primary_key ' : '';
$flags .= 'multiple_key ';
* Returns information about a table or a result set.
* NOTE: only supports 'table' and 'flags' if <var>$result</var>
* @param object|string $result DB_result object from a query or a
* string containing the name of a table
* @param int $mode a valid tableInfo mode
* @return array an associative array with the information requested
* or an error object if something is wrong
* @see DB_common::tableInfo()
if (isset ($result->result )) {
* Probably received a result object.
* Extract the result resource identifier.
* Probably received a table name.
* Create a result resource identifier.
$id = @pg_exec ($this->connection, " SELECT * FROM $result LIMIT 0" );
* Probably received a result resource identifier.
* Deprecated. Here for compatibility only.
$case_func = 'strtolower';
$count = @pg_numfields ($id);
// made this IF due to performance (one if is faster than $count if's)
for ($i=0; $i< $count; $i++ ) {
$res[$i]['table'] = $got_string ? $case_func($result) : '';
$res[$i]['name'] = $case_func(@pg_fieldname ($id, $i));
$res[$i]['type'] = @pg_fieldtype ($id, $i);
$res[$i]['len'] = @pg_fieldsize ($id, $i);
$res[$i]['flags'] = $got_string ? $this->_pgFieldflags ($id, $i, $result) : '';
$res['num_fields']= $count;
for ($i=0; $i< $count; $i++ ) {
$res[$i]['table'] = $got_string ? $case_func($result) : '';
$res[$i]['name'] = $case_func(@pg_fieldname ($id, $i));
$res[$i]['type'] = @pg_fieldtype ($id, $i);
$res[$i]['len'] = @pg_fieldsize ($id, $i);
$res[$i]['flags'] = $got_string ? $this->_pgFieldFlags ($id, $i, $result) : '';
$res['order'][$res[$i]['name']] = $i;
$res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
// free the result only if we were called on a table
* Returns the query needed to get some backend info
* @param string $type What kind of info you want to retrieve
* @return string The SQL query string
return "SELECT c.relname as \"Name\"
FROM pg_class c, pg_user u
WHERE c.relowner = u.usesysid AND c.relkind = 'r'
AND not exists (select 1 from pg_views where viewname = c.relname)
SELECT c.relname as \"Name\"
AND not exists (select 1 from pg_views where viewname = c.relname)
AND not exists (select 1 from pg_user where usesysid = c.relowner)
AND c.relname !~ '^pg_'";
// Table cols: viewname | viewowner | definition
return 'SELECT viewname FROM pg_views';
// cols: usename |usesysid|usecreatedb|usetrace|usesuper|usecatupd|passwd |valuntil
return 'SELECT usename FROM pg_user';
return 'SELECT datname FROM pg_database';
return 'SELECT proname FROM pg_proc';
Documentation generated on Mon, 11 Mar 2019 10:14:54 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|