Source for file adodb-postgres64.inc.php
Documentation is available at adodb-postgres64.inc.php
V4.97 22 Jan 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones.
08 Nov 2000 jlim - Minor corrections, removing mysql stuff
09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>
jlim - changed concat operator to || and data types to MetaType to match documented pgsql types
see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm
22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>
27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>
15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk.
31 Jan 2002 jlim - finally installed postgresql. testing
01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type
See http://www.varlena.com/varlena/GeneralBits/47.php
-- What indexes are on my table?
select * from pg_indexes where tablename = 'tablename';
-- What triggers are on my table?
select c.relname as "Table", t.tgname as "Trigger Name",
t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
p.proname as "Function Name"
from pg_trigger t, pg_class c, pg_class cc, pg_proc p
where t.tgfoid = p.oid and t.tgrelid = c.oid
and t.tgconstrrelid = cc.oid
and c.relname = 'tablename';
-- What constraints are on my table?
select r.relname as "Table", c.conname as "Constraint Name",
contype as "Constraint Type", conkey as "Key Columns",
confkey as "Foreign Columns", consrc as "Source"
from pg_class r, pg_constraint c
and relname = 'tablename';
if ($len == 0) return "''";
if (strncmp($s,"'",1) === 0 && substr($s,$len- 1) == "'") return $s; // already quoted
var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
select viewname,'V' from pg_views where viewname not like 'pg\_%'";
//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
var $isoDates = true; // accepts dates in ISO format
var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
FROM pg_class c, pg_attribute a,pg_type t
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// used when schema defined
var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
and c.relnamespace=n.oid and n.nspname='%s'
and a.attname not like '....%%' AND a.attnum > 0
AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
// get primary key etc -- from Freek Dijkstra
var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
// below suggested by Freek Dijkstra
var $true = 'TRUE'; // string that represents TRUE for a database
var $false = 'FALSE'; // string that represents FALSE for a database
var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
var $random = 'random()'; /// random function
var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
// http://bugs.php.net/bug.php?id=25404
var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
// The last (fmtTimeStamp is not entirely correct:
// PostgreSQL also has support for time zones,
// and writes these time in this format: "2001-03-01 18:59:26+02".
// There is no code for the "+02" time zone information, so I just left that out.
// I'm not familiar enough with both ADODB as well as Postgres
// to know what the concequences are. The other values are correct (wheren't in 0.94)
// changes the metaColumnsSQL, adds columns: attnum[6]
if (isset ($this->version)) return $this->version;
$arr['description'] = $this->GetOne("select version()");
function IfNull( $field, $ifNull )
return " coalesce($field, $ifNull) ";
// get the last id - never tested
$result= pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
$arr = @pg_fetch_row($result,0);
if (isset ($arr[0])) return $arr[0];
/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
Using a OID as a unique identifier is not generally wise.
Unless you are very careful, you might end up with a tuple having
a different OID if a database must be reloaded. */
// to really return the id, we need the table and column-name, else we can only return the oid != id
//return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT $column FROM $table WHERE oid=".(int)$oid);
return empty($table) || empty($column) ? $oid : $this->pg_insert_id($table, $column);
// I get this error with PHP before 4.0.6 - jlim
// Warning: This compilation does not support pg_cmdtuples() in adodb-postgres.inc.php on line 44
function RowLock($tables,$where,$flds= '1 as ignore')
return $this->GetOne("select $flds from $tables where $where for update");
function &MetaTables($ttype= false,$showSchema= false,$mask= false)
if ($info['version'] >= 7.3) {
$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
and schemaname not in ( 'pg_catalog','information_schema')
select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
if ($info['version']>= 7.3)
select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') ";
select tablename,'T' from pg_tables where tablename like $mask
select viewname,'V' from pg_views where viewname like $mask";
// if magic quotes disabled, use pg_escape_string()
function qstr($s,$magic_quotes= false)
return "'". pg_escape_string($s). "'";
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\\000"),$s);
// undo magic quotes for "
// Format date column in sql string given an input format that understands Y M D
$s = 'TO_CHAR('. $col. ",'";
for ($i= 0; $i < $len; $i++ ) {
// handle escape characters...
* Load a Large Object from a file
* - the procedure stores the object id in the table and imports the object using
* postgres proprietary blob handling routines
* contributed by Mattia Rossi mattia@technologist.com
* modified for safe mode by juraj chlebec
pg_lo_write($handle, $contents);
// $oid = pg_lo_import ($path);
* Deletes/Unlinks a Blob from the database, otherwise it
* Returns TRUE on success or FALSE on failure.
* contributed by Todd Rogers todd#windfox.net
$result = @pg_lo_unlink($blob);
Hueristic - not guaranteed to work.
* If an OID is detected, then we use pg_lo_* to open the oid file and read the
* real blob from the db using the oid supplied as a parameter. If you are storing
* blobs using bytea, we autodetect and process it so this function is not needed.
* contributed by Mattia Rossi mattia@technologist.com
* see http://www.postgresql.org/idocs/index.php?largeobjects.html
* Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
* added maxsize parameter, which defaults to $db->maxblobsize if not defined.
function BlobDecode($blob,$maxsize= false,$hastrans= true)
if (!$this->GuessOID($blob)) return $blob;
$realblob = @pg_loread($fd,$maxsize);
See http://www.postgresql.org/idocs/index.php?datatype-binary.html
NOTE: SQL string literals (input strings) must be preceded with two backslashes
due to the fact that they must pass through two parsers in the PostgreSQL
/*92=backslash, 0=null, 39=single-quote*/
$badch = array(chr(92),chr(0),chr(39)); # \ null '
$fixch = array('\\\\134','\\\\000','\\\\047');
return adodb_str_replace($badch,$fixch,$blob);
// note that there is a pg_escape_bytea function only for php 4.2.0 or later
// assumes bytea for blob, and varchar for clob
function UpdateBlob($table,$column,$val,$where,$blobtype= 'BLOB')
if ($blobtype == 'CLOB') {
return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
// do not use bind params which uses qstr(), as blobencode() already quotes data
return $this->Execute("UPDATE $table SET $column='". $this->BlobEncode($val). "'::bytea WHERE $where");
if (!$date) $date = $this->sysDate;
else if (strncmp($date,"'",1) == 0) {
if (10 <= $len && $len <= 12) $date = 'date '. $date;
else $date = 'timestamp '. $date;
return "($date+interval'$dayFraction days')";
// for schema support, pass in the $table param "$schema.$tabname".
// converts field names to lowercase, $upper is ignored
// see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = $save;
// If we want the primary keys, we have to issue a separate query
// Of course, a modified version of the metaColumnsSQL query using a
// LEFT JOIN would have been much more elegant, but postgres does
// not support OUTER JOINS. So here is the clumsy way.
// fetch all result in once for performance.
$keys = & $rskey->GetArray();
$ADODB_FETCH_MODE = $save;
$ADODB_FETCH_MODE = $save;
$num = $rsdef->fields['num'];
$s = $rsdef->fields['def'];
if (strpos($s,'::')=== false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$fld->attnum = $rs->fields[6];
if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]- 4;
if ($fld->max_length <= 0) $fld->max_length = - 1;
if ($fld->type == 'numeric') {
$fld->scale = $fld->max_length & 0xFFFF;
// 5 hasdefault; 6 num-of-column
$fld->has_default = ($rs->fields[5] == 't');
$fld->default_value = $rsdefa[$rs->fields[6]];
$fld->not_null = $rs->fields[4] == 't';
if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
$fld->primary_key = true;
if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
$fld->unique = true; // What name is more compatible?
else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
global $ADODB_FETCH_MODE;
if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
$sql .= ' AND i.indisprimary=false;';
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = $save;
//3rd param is use attnum,
// see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
while ($row = $rs->FetchRow()) {
foreach (explode(' ', $row[2]) as $col) {
$columns[] = $col_names[$col];
$indexes[$row[0]] = array(
'unique' => ($row[1] == 't'),
// $db->Connect("host=host1 user=user1 password=secret port=4341");
// $db->Connect('host1','user1','secret');
function _connect($str,$user= '',$pwd= '',$db= '',$ctype= 0)
if ($user || $pwd || $db) {
if (strlen($db) == 0) $db = 'template1';
$host = split(":", $str);
if (isset ($host[1])) $str .= " port=$host[1]";
else if (!empty($this->port)) $str .= " port=". $this->port;
if ($user) $str .= " user=". $user;
if ($pwd) $str .= " password=". $pwd;
if ($db) $str .= " dbname=". $db;
//if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
if ($ctype === 1) { // persistent
if ($ctype === - 1) { // nconnect, we trick pgsql ext by changing the connection str
if (empty($ncnt)) $ncnt = 1;
$this->Execute("set datestyle='ISO'");
$this->pgVersion = (float) substr($info['version'],0,3);
if ($this->pgVersion >= 7.1) { // good till version 999
$this->_nestedSQL = true;
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,- 1);
// $db->PConnect("host=host1 user=user1 password=secret port=4341");
// $db->PConnect('host1','user1','secret');
function _pconnect($str,$user= '',$pwd= '',$db= '')
return $this->_connect($str,$user,$pwd,$db,1);
// returns queryID or false
function _query($sql,$inputarr)
It appears that PREPARE/EXECUTE is slower for many queries.
For query executed 1000 times:
"select id,firstname,lastname from adoxyz
where firstname not like ? and lastname not like ? and id = ?"
with plan = 1.51861286163 secs
no plan = 1.26903700829 secs
foreach($inputarr as $v) {
if ($execp) $execp .= ',';
if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
if ($execp) $exsql = "EXECUTE $plan ($execp)";
else $exsql = "EXECUTE $plan";
# Perhaps plan does not exist? Prepare/compile plan.
foreach($inputarr as $v) {
if ($params) $params .= ',';
$s = "PREPARE $plan ($params) AS ". substr($sql,0,strlen($sql)- 2);
//echo $this->ErrorMsg();
// check if no data returned, then no need to create real recordset
if ($rez && pg_numfields($rez) <= 0) {
else return 'Database connection failed';
/* Returns: the last error message from previous database operation */
* Maximum size of C field
return 1000000000; // should be 1 Gb?
* Maximum size of X field
return 1000000000; // should be 1 Gb?
/*--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------*/
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
default: $this->fetchMode = PGSQL_BOTH; break;
$this->adodbFetchMode = $mode;
$this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):- 1;
// cache types for blob decode check
// apparently pg_fieldtype actually performs an sql query on the database to get the type.
if (pg_fieldtype($qid,$i) == 'bytea') {
$this->_blobArr[$i] = pg_fieldname($qid,$i);
/* Use associative array to get fields array */
$o->name = @pg_fieldname($this->_queryID,$off);
$o->type = @pg_fieldtype($this->_queryID,$off);
$o->max_length = @pg_fieldsize($this->_queryID,$off);
return @pg_fetch_row($this->_queryID,$row);
eval ('$realblob="'. adodb_str_replace(array('"','$'),array('\"','\$'),$blob). '";');
// 10% speedup to move MoveNext to child class
function MetaType($t,$len=- 1,$fieldobj= false)
$len = $fieldobj->max_length;
case 'MONEY': // stupid, postgres expects money to be a string
if ($len <= $this->blobSize) return 'C';
case 'IMAGE': // user defined type
case 'BLOB': // user defined type
case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
case 'TIMESTAMP WITHOUT TIME ZONE':
empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
|