1<?php
2
3/*
4V4.65 22 July 2005  (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
5  Released under both BSD license and Lesser GPL library license.
6  Whenever there is any discrepancy between the two licenses,
7  the BSD license will take precedence.
8  Set tabs to 8.
9
10*/
11
12class ADODB_pdo_pgsql extends ADODB_pdo {
13var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
14    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
15	and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
16	 'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
17	union
18        select viewname,'V' from pg_views where viewname not like 'pg\_%'";
19	//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
20	var $isoDates = true; // accepts dates in ISO format
21	var $sysDate = "CURRENT_DATE";
22	var $sysTimeStamp = "CURRENT_TIMESTAMP";
23	var $blobEncodeType = 'C';
24	var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
25		FROM pg_class c, pg_attribute a,pg_type t
26		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
27AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
28
29	// used when schema defined
30	var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
31FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
32WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
33 and c.relnamespace=n.oid and n.nspname='%s'
34	and a.attname not like '....%%' AND a.attnum > 0
35	AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
36
37	// get primary key etc -- from Freek Dijkstra
38	var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
39	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'";
40
41	var $hasAffectedRows = true;
42	var $hasLimit = false;	// set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
43	// below suggested by Freek Dijkstra
44	var $true = 't';		// string that represents TRUE for a database
45	var $false = 'f';		// string that represents FALSE for a database
46	var $fmtDate = "'Y-m-d'";	// used by DBDate() as the default date format used by the database
47	var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
48	var $hasMoveFirst = true;
49	var $hasGenID = true;
50	var $_genIDSQL = "SELECT NEXTVAL('%s')";
51	var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
52	var $_dropSeqSQL = "DROP SEQUENCE %s";
53	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";
54	var $random = 'random()';		/// random function
55	var $concat_operator='||';
56
57	function _init($parentDriver)
58	{
59
60		$parentDriver->hasTransactions = false;
61	}
62
63	function ServerInfo()
64	{
65		$arr['description'] = ADOConnection::GetOne("select version()");
66		$arr['version'] = ADOConnection::_findvers($arr['description']);
67		return $arr;
68	}
69
70	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
71	{
72		 $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
73		 $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';
74		 if ($secs2cache)
75		  	$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
76		 else
77		  	$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
78
79		return $rs;
80	}
81
82	function &MetaTables($ttype=false,$showSchema=false,$mask=false)
83	{
84		$info = $this->ServerInfo();
85		if ($info['version'] >= 7.3) {
86	    	$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
87			  and schemaname  not in ( 'pg_catalog','information_schema')
88	union
89        select viewname,'V' from pg_views where viewname not like 'pg\_%'  and schemaname  not in ( 'pg_catalog','information_schema') ";
90		}
91		if ($mask) {
92			$save = $this->metaTablesSQL;
93			$mask = $this->qstr(strtolower($mask));
94			if ($info['version']>=7.3)
95				$this->metaTablesSQL = "
96select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
97 union
98select viewname,'V' from pg_views where viewname like $mask and schemaname  not in ( 'pg_catalog','information_schema')  ";
99			else
100				$this->metaTablesSQL = "
101select tablename,'T' from pg_tables where tablename like $mask
102 union
103select viewname,'V' from pg_views where viewname like $mask";
104		}
105		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
106
107		if ($mask) {
108			$this->metaTablesSQL = $save;
109		}
110		return $ret;
111	}
112
113	function &MetaColumns($table,$normalize=true)
114	{
115	global $ADODB_FETCH_MODE;
116
117		$schema = false;
118		$this->_findschema($table,$schema);
119
120		if ($normalize) $table = strtolower($table);
121
122		$save = $ADODB_FETCH_MODE;
123		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
124		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
125
126		if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
127		else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
128		if (isset($savem)) $this->SetFetchMode($savem);
129		$ADODB_FETCH_MODE = $save;
130
131		if ($rs === false) {
132			$false = false;
133			return $false;
134		}
135		if (!empty($this->metaKeySQL)) {
136			// If we want the primary keys, we have to issue a separate query
137			// Of course, a modified version of the metaColumnsSQL query using a
138			// LEFT JOIN would have been much more elegant, but postgres does
139			// not support OUTER JOINS. So here is the clumsy way.
140
141			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
142
143			$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
144			// fetch all result in once for performance.
145			$keys =& $rskey->GetArray();
146			if (isset($savem)) $this->SetFetchMode($savem);
147			$ADODB_FETCH_MODE = $save;
148
149			$rskey->Close();
150			unset($rskey);
151		}
152
153		$rsdefa = array();
154		if (!empty($this->metaDefaultsSQL)) {
155			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
156			$sql = sprintf($this->metaDefaultsSQL, ($table));
157			$rsdef = $this->Execute($sql);
158			if (isset($savem)) $this->SetFetchMode($savem);
159			$ADODB_FETCH_MODE = $save;
160
161			if ($rsdef) {
162				while (!$rsdef->EOF) {
163					$num = $rsdef->fields['num'];
164					$s = $rsdef->fields['def'];
165					if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
166						$s = substr($s, 1);
167						$s = substr($s, 0, strlen($s) - 1);
168					}
169
170					$rsdefa[$num] = $s;
171					$rsdef->MoveNext();
172				}
173			} else {
174				ADOConnection::outp( "==> SQL => " . $sql);
175			}
176			unset($rsdef);
177		}
178
179		$retarr = array();
180		while (!$rs->EOF) {
181			$fld = new ADOFieldObject();
182			$fld->name = $rs->fields[0];
183			$fld->type = $rs->fields[1];
184			$fld->max_length = $rs->fields[2];
185			if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
186			if ($fld->max_length <= 0) $fld->max_length = -1;
187			if ($fld->type == 'numeric') {
188				$fld->scale = $fld->max_length & 0xFFFF;
189				$fld->max_length >>= 16;
190			}
191			// dannym
192			// 5 hasdefault; 6 num-of-column
193			$fld->has_default = ($rs->fields[5] == 't');
194			if ($fld->has_default) {
195				$fld->default_value = $rsdefa[$rs->fields[6]];
196			}
197
198			//Freek
199			if ($rs->fields[4] == $this->true) {
200				$fld->not_null = true;
201			}
202
203			// Freek
204			if (is_array($keys)) {
205				foreach($keys as $key) {
206					if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true)
207						$fld->primary_key = true;
208					if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true)
209						$fld->unique = true; // What name is more compatible?
210				}
211			}
212
213			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
214			else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
215
216			$rs->MoveNext();
217		}
218		$rs->Close();
219		if (empty($retarr)) {
220			$false = false;
221			return $false;
222		} else return $retarr;
223
224	}
225
226}
227
228?>
229