PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/adodb/drivers/adodb-postgres64.inc.php

https://github.com/Fusion/lenses
PHP | 1064 lines | 893 code | 67 blank | 104 comment | 90 complexity | 6c20cb96478c8cb8d61bc98e6f9f1bae MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /*
  3. V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
  4. Released under both BSD license and Lesser GPL library license.
  5. Whenever there is any discrepancy between the two licenses,
  6. the BSD license will take precedence.
  7. Set tabs to 8.
  8. Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones.
  9. 08 Nov 2000 jlim - Minor corrections, removing mysql stuff
  10. 09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>
  11. jlim - changed concat operator to || and data types to MetaType to match documented pgsql types
  12. see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm
  13. 22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>
  14. 27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>
  15. 15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk.
  16. 31 Jan 2002 jlim - finally installed postgresql. testing
  17. 01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type
  18. See http://www.varlena.com/varlena/GeneralBits/47.php
  19. -- What indexes are on my table?
  20. select * from pg_indexes where tablename = 'tablename';
  21. -- What triggers are on my table?
  22. select c.relname as "Table", t.tgname as "Trigger Name",
  23. t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
  24. t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
  25. p.proname as "Function Name"
  26. from pg_trigger t, pg_class c, pg_class cc, pg_proc p
  27. where t.tgfoid = p.oid and t.tgrelid = c.oid
  28. and t.tgconstrrelid = cc.oid
  29. and c.relname = 'tablename';
  30. -- What constraints are on my table?
  31. select r.relname as "Table", c.conname as "Constraint Name",
  32. contype as "Constraint Type", conkey as "Key Columns",
  33. confkey as "Foreign Columns", consrc as "Source"
  34. from pg_class r, pg_constraint c
  35. where r.oid = c.conrelid
  36. and relname = 'tablename';
  37. */
  38. // security - hide paths
  39. if (!defined('ADODB_DIR')) die();
  40. function adodb_addslashes($s)
  41. {
  42. $len = strlen($s);
  43. if ($len == 0) return "''";
  44. if (strncmp($s,"'",1) === 0 && substr($s,$len-1) == "'") return $s; // already quoted
  45. return "'".addslashes($s)."'";
  46. }
  47. class ADODB_postgres64 extends ADOConnection{
  48. var $databaseType = 'postgres64';
  49. var $dataProvider = 'postgres';
  50. var $hasInsertID = true;
  51. var $_resultid = false;
  52. var $concat_operator='||';
  53. var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
  54. var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
  55. and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
  56. 'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
  57. union
  58. select viewname,'V' from pg_views where viewname not like 'pg\_%'";
  59. //"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
  60. var $isoDates = true; // accepts dates in ISO format
  61. var $sysDate = "CURRENT_DATE";
  62. var $sysTimeStamp = "CURRENT_TIMESTAMP";
  63. var $blobEncodeType = 'C';
  64. var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
  65. FROM pg_class c, pg_attribute a,pg_type t
  66. WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
  67. AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
  68. // used when schema defined
  69. var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
  70. FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
  71. WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
  72. and c.relnamespace=n.oid and n.nspname='%s'
  73. and a.attname not like '....%%' AND a.attnum > 0
  74. AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
  75. // get primary key etc -- from Freek Dijkstra
  76. var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
  77. 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'";
  78. var $hasAffectedRows = true;
  79. var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  80. // below suggested by Freek Dijkstra
  81. var $true = 'TRUE'; // string that represents TRUE for a database
  82. var $false = 'FALSE'; // string that represents FALSE for a database
  83. var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database
  84. var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
  85. var $hasMoveFirst = true;
  86. var $hasGenID = true;
  87. var $_genIDSQL = "SELECT NEXTVAL('%s')";
  88. var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
  89. var $_dropSeqSQL = "DROP SEQUENCE %s";
  90. 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";
  91. var $random = 'random()'; /// random function
  92. var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
  93. // http://bugs.php.net/bug.php?id=25404
  94. var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
  95. var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
  96. // The last (fmtTimeStamp is not entirely correct:
  97. // PostgreSQL also has support for time zones,
  98. // and writes these time in this format: "2001-03-01 18:59:26+02".
  99. // There is no code for the "+02" time zone information, so I just left that out.
  100. // I'm not familiar enough with both ADODB as well as Postgres
  101. // to know what the concequences are. The other values are correct (wheren't in 0.94)
  102. // -- Freek Dijkstra
  103. function ADODB_postgres64()
  104. {
  105. // changes the metaColumnsSQL, adds columns: attnum[6]
  106. }
  107. function ServerInfo()
  108. {
  109. if (isset($this->version)) return $this->version;
  110. $arr['description'] = $this->GetOne("select version()");
  111. $arr['version'] = ADOConnection::_findvers($arr['description']);
  112. $this->version = $arr;
  113. return $arr;
  114. }
  115. function IfNull( $field, $ifNull )
  116. {
  117. return " coalesce($field, $ifNull) ";
  118. }
  119. // get the last id - never tested
  120. function pg_insert_id($tablename,$fieldname)
  121. {
  122. $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
  123. if ($result) {
  124. $arr = @pg_fetch_row($result,0);
  125. pg_freeresult($result);
  126. if (isset($arr[0])) return $arr[0];
  127. }
  128. return false;
  129. }
  130. /* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
  131. Using a OID as a unique identifier is not generally wise.
  132. Unless you are very careful, you might end up with a tuple having
  133. a different OID if a database must be reloaded. */
  134. function _insertid($table,$column)
  135. {
  136. if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
  137. $oid = pg_getlastoid($this->_resultid);
  138. // to really return the id, we need the table and column-name, else we can only return the oid != id
  139. return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT $column FROM $table WHERE oid=".(int)$oid);
  140. }
  141. // I get this error with PHP before 4.0.6 - jlim
  142. // Warning: This compilation does not support pg_cmdtuples() in adodb-postgres.inc.php on line 44
  143. function _affectedrows()
  144. {
  145. if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
  146. return pg_cmdtuples($this->_resultid);
  147. }
  148. // returns true/false
  149. function BeginTrans()
  150. {
  151. if ($this->transOff) return true;
  152. $this->transCnt += 1;
  153. return @pg_Exec($this->_connectionID, "begin ".$this->_transmode);
  154. }
  155. function RowLock($tables,$where,$flds='1 as ignore')
  156. {
  157. if (!$this->transCnt) $this->BeginTrans();
  158. return $this->GetOne("select $flds from $tables where $where for update");
  159. }
  160. // returns true/false.
  161. function CommitTrans($ok=true)
  162. {
  163. if ($this->transOff) return true;
  164. if (!$ok) return $this->RollbackTrans();
  165. $this->transCnt -= 1;
  166. return @pg_Exec($this->_connectionID, "commit");
  167. }
  168. // returns true/false
  169. function RollbackTrans()
  170. {
  171. if ($this->transOff) return true;
  172. $this->transCnt -= 1;
  173. return @pg_Exec($this->_connectionID, "rollback");
  174. }
  175. function MetaTables($ttype=false,$showSchema=false,$mask=false)
  176. {
  177. $info = $this->ServerInfo();
  178. if ($info['version'] >= 7.3) {
  179. $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
  180. and schemaname not in ( 'pg_catalog','information_schema')
  181. union
  182. select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
  183. }
  184. if ($mask) {
  185. $save = $this->metaTablesSQL;
  186. $mask = $this->qstr(strtolower($mask));
  187. if ($info['version']>=7.3)
  188. $this->metaTablesSQL = "
  189. select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
  190. union
  191. select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') ";
  192. else
  193. $this->metaTablesSQL = "
  194. select tablename,'T' from pg_tables where tablename like $mask
  195. union
  196. select viewname,'V' from pg_views where viewname like $mask";
  197. }
  198. $ret = ADOConnection::MetaTables($ttype,$showSchema);
  199. if ($mask) {
  200. $this->metaTablesSQL = $save;
  201. }
  202. return $ret;
  203. }
  204. // if magic quotes disabled, use pg_escape_string()
  205. function qstr($s,$magic_quotes=false)
  206. {
  207. if (!$magic_quotes) {
  208. if (ADODB_PHPVER >= 0x5200) {
  209. return "'".pg_escape_string($this->_connectionID,$s)."'";
  210. }
  211. if (ADODB_PHPVER >= 0x4200) {
  212. return "'".pg_escape_string($s)."'";
  213. }
  214. if ($this->replaceQuote[0] == '\\'){
  215. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\\000"),$s);
  216. }
  217. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  218. }
  219. // undo magic quotes for "
  220. $s = str_replace('\\"','"',$s);
  221. return "'$s'";
  222. }
  223. // Format date column in sql string given an input format that understands Y M D
  224. function SQLDate($fmt, $col=false)
  225. {
  226. if (!$col) $col = $this->sysTimeStamp;
  227. $s = 'TO_CHAR('.$col.",'";
  228. $len = strlen($fmt);
  229. for ($i=0; $i < $len; $i++) {
  230. $ch = $fmt[$i];
  231. switch($ch) {
  232. case 'Y':
  233. case 'y':
  234. $s .= 'YYYY';
  235. break;
  236. case 'Q':
  237. case 'q':
  238. $s .= 'Q';
  239. break;
  240. case 'M':
  241. $s .= 'Mon';
  242. break;
  243. case 'm':
  244. $s .= 'MM';
  245. break;
  246. case 'D':
  247. case 'd':
  248. $s .= 'DD';
  249. break;
  250. case 'H':
  251. $s.= 'HH24';
  252. break;
  253. case 'h':
  254. $s .= 'HH';
  255. break;
  256. case 'i':
  257. $s .= 'MI';
  258. break;
  259. case 's':
  260. $s .= 'SS';
  261. break;
  262. case 'a':
  263. case 'A':
  264. $s .= 'AM';
  265. break;
  266. case 'w':
  267. $s .= 'D';
  268. break;
  269. case 'l':
  270. $s .= 'DAY';
  271. break;
  272. case 'W':
  273. $s .= 'WW';
  274. break;
  275. default:
  276. // handle escape characters...
  277. if ($ch == '\\') {
  278. $i++;
  279. $ch = substr($fmt,$i,1);
  280. }
  281. if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
  282. else $s .= '"'.$ch.'"';
  283. }
  284. }
  285. return $s. "')";
  286. }
  287. /*
  288. * Load a Large Object from a file
  289. * - the procedure stores the object id in the table and imports the object using
  290. * postgres proprietary blob handling routines
  291. *
  292. * contributed by Mattia Rossi mattia@technologist.com
  293. * modified for safe mode by juraj chlebec
  294. */
  295. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  296. {
  297. pg_exec ($this->_connectionID, "begin");
  298. $fd = fopen($path,'r');
  299. $contents = fread($fd,filesize($path));
  300. fclose($fd);
  301. $oid = pg_lo_create($this->_connectionID);
  302. $handle = pg_lo_open($this->_connectionID, $oid, 'w');
  303. pg_lo_write($handle, $contents);
  304. pg_lo_close($handle);
  305. // $oid = pg_lo_import ($path);
  306. pg_exec($this->_connectionID, "commit");
  307. $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype);
  308. $rez = !empty($rs);
  309. return $rez;
  310. }
  311. /*
  312. * Deletes/Unlinks a Blob from the database, otherwise it
  313. * will be left behind
  314. *
  315. * Returns TRUE on success or FALSE on failure.
  316. *
  317. * contributed by Todd Rogers todd#windfox.net
  318. */
  319. function BlobDelete( $blob )
  320. {
  321. pg_exec ($this->_connectionID, "begin");
  322. $result = @pg_lo_unlink($blob);
  323. pg_exec ($this->_connectionID, "commit");
  324. return( $result );
  325. }
  326. /*
  327. Hueristic - not guaranteed to work.
  328. */
  329. function GuessOID($oid)
  330. {
  331. if (strlen($oid)>16) return false;
  332. return is_numeric($oid);
  333. }
  334. /*
  335. * If an OID is detected, then we use pg_lo_* to open the oid file and read the
  336. * real blob from the db using the oid supplied as a parameter. If you are storing
  337. * blobs using bytea, we autodetect and process it so this function is not needed.
  338. *
  339. * contributed by Mattia Rossi mattia@technologist.com
  340. *
  341. * see http://www.postgresql.org/idocs/index.php?largeobjects.html
  342. *
  343. * Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
  344. * added maxsize parameter, which defaults to $db->maxblobsize if not defined.
  345. */
  346. function BlobDecode($blob,$maxsize=false,$hastrans=true)
  347. {
  348. if (!$this->GuessOID($blob)) return $blob;
  349. if ($hastrans) @pg_exec($this->_connectionID,"begin");
  350. $fd = @pg_lo_open($this->_connectionID,$blob,"r");
  351. if ($fd === false) {
  352. if ($hastrans) @pg_exec($this->_connectionID,"commit");
  353. return $blob;
  354. }
  355. if (!$maxsize) $maxsize = $this->maxblobsize;
  356. $realblob = @pg_loread($fd,$maxsize);
  357. @pg_loclose($fd);
  358. if ($hastrans) @pg_exec($this->_connectionID,"commit");
  359. return $realblob;
  360. }
  361. /*
  362. See http://www.postgresql.org/idocs/index.php?datatype-binary.html
  363. NOTE: SQL string literals (input strings) must be preceded with two backslashes
  364. due to the fact that they must pass through two parsers in the PostgreSQL
  365. backend.
  366. */
  367. function BlobEncode($blob)
  368. {
  369. if (ADODB_PHPVER >= 0x5200) return pg_escape_bytea($this->_connectionID, $blob);
  370. if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
  371. /*92=backslash, 0=null, 39=single-quote*/
  372. $badch = array(chr(92),chr(0),chr(39)); # \ null '
  373. $fixch = array('\\\\134','\\\\000','\\\\047');
  374. return adodb_str_replace($badch,$fixch,$blob);
  375. // note that there is a pg_escape_bytea function only for php 4.2.0 or later
  376. }
  377. // assumes bytea for blob, and varchar for clob
  378. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  379. {
  380. if ($blobtype == 'CLOB') {
  381. return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
  382. }
  383. // do not use bind params which uses qstr(), as blobencode() already quotes data
  384. return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
  385. }
  386. function OffsetDate($dayFraction,$date=false)
  387. {
  388. if (!$date) $date = $this->sysDate;
  389. else if (strncmp($date,"'",1) == 0) {
  390. $len = strlen($date);
  391. if (10 <= $len && $len <= 12) $date = 'date '.$date;
  392. else $date = 'timestamp '.$date;
  393. }
  394. return "($date+interval'$dayFraction days')";
  395. }
  396. // for schema support, pass in the $table param "$schema.$tabname".
  397. // converts field names to lowercase, $upper is ignored
  398. // see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info
  399. function MetaColumns($table,$normalize=true)
  400. {
  401. global $ADODB_FETCH_MODE;
  402. $schema = false;
  403. $false = false;
  404. $this->_findschema($table,$schema);
  405. if ($normalize) $table = strtolower($table);
  406. $save = $ADODB_FETCH_MODE;
  407. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  408. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  409. if ($schema) $rs = $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
  410. else $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
  411. if (isset($savem)) $this->SetFetchMode($savem);
  412. $ADODB_FETCH_MODE = $save;
  413. if ($rs === false) {
  414. return $false;
  415. }
  416. if (!empty($this->metaKeySQL)) {
  417. // If we want the primary keys, we have to issue a separate query
  418. // Of course, a modified version of the metaColumnsSQL query using a
  419. // LEFT JOIN would have been much more elegant, but postgres does
  420. // not support OUTER JOINS. So here is the clumsy way.
  421. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  422. $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
  423. // fetch all result in once for performance.
  424. $keys = $rskey->GetArray();
  425. if (isset($savem)) $this->SetFetchMode($savem);
  426. $ADODB_FETCH_MODE = $save;
  427. $rskey->Close();
  428. unset($rskey);
  429. }
  430. $rsdefa = array();
  431. if (!empty($this->metaDefaultsSQL)) {
  432. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  433. $sql = sprintf($this->metaDefaultsSQL, ($table));
  434. $rsdef = $this->Execute($sql);
  435. if (isset($savem)) $this->SetFetchMode($savem);
  436. $ADODB_FETCH_MODE = $save;
  437. if ($rsdef) {
  438. while (!$rsdef->EOF) {
  439. $num = $rsdef->fields['num'];
  440. $s = $rsdef->fields['def'];
  441. if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
  442. $s = substr($s, 1);
  443. $s = substr($s, 0, strlen($s) - 1);
  444. }
  445. $rsdefa[$num] = $s;
  446. $rsdef->MoveNext();
  447. }
  448. } else {
  449. ADOConnection::outp( "==> SQL => " . $sql);
  450. }
  451. unset($rsdef);
  452. }
  453. $retarr = array();
  454. while (!$rs->EOF) {
  455. $fld = new ADOFieldObject();
  456. $fld->name = $rs->fields[0];
  457. $fld->type = $rs->fields[1];
  458. $fld->max_length = $rs->fields[2];
  459. $fld->attnum = $rs->fields[6];
  460. if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
  461. if ($fld->max_length <= 0) $fld->max_length = -1;
  462. if ($fld->type == 'numeric') {
  463. $fld->scale = $fld->max_length & 0xFFFF;
  464. $fld->max_length >>= 16;
  465. }
  466. // dannym
  467. // 5 hasdefault; 6 num-of-column
  468. $fld->has_default = ($rs->fields[5] == 't');
  469. if ($fld->has_default) {
  470. $fld->default_value = $rsdefa[$rs->fields[6]];
  471. }
  472. //Freek
  473. $fld->not_null = $rs->fields[4] == 't';
  474. // Freek
  475. if (is_array($keys)) {
  476. foreach($keys as $key) {
  477. if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
  478. $fld->primary_key = true;
  479. if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
  480. $fld->unique = true; // What name is more compatible?
  481. }
  482. }
  483. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  484. else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
  485. $rs->MoveNext();
  486. }
  487. $rs->Close();
  488. if (empty($retarr))
  489. return $false;
  490. else
  491. return $retarr;
  492. }
  493. function MetaIndexes ($table, $primary = FALSE)
  494. {
  495. global $ADODB_FETCH_MODE;
  496. $schema = false;
  497. $this->_findschema($table,$schema);
  498. if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
  499. $sql = '
  500. SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
  501. FROM pg_catalog.pg_class c
  502. JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
  503. JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
  504. ,pg_namespace n
  505. WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
  506. } else {
  507. $sql = '
  508. SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
  509. FROM pg_catalog.pg_class c
  510. JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
  511. JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
  512. WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
  513. }
  514. if ($primary == FALSE) {
  515. $sql .= ' AND i.indisprimary=false;';
  516. }
  517. $save = $ADODB_FETCH_MODE;
  518. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  519. if ($this->fetchMode !== FALSE) {
  520. $savem = $this->SetFetchMode(FALSE);
  521. }
  522. $rs = $this->Execute(sprintf($sql,$table,$table,$schema));
  523. if (isset($savem)) {
  524. $this->SetFetchMode($savem);
  525. }
  526. $ADODB_FETCH_MODE = $save;
  527. if (!is_object($rs)) {
  528. $false = false;
  529. return $false;
  530. }
  531. $col_names = $this->MetaColumnNames($table,true,true);
  532. //3rd param is use attnum,
  533. // see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
  534. $indexes = array();
  535. while ($row = $rs->FetchRow()) {
  536. $columns = array();
  537. foreach (explode(' ', $row[2]) as $col) {
  538. $columns[] = $col_names[$col];
  539. }
  540. $indexes[$row[0]] = array(
  541. 'unique' => ($row[1] == 't'),
  542. 'columns' => $columns
  543. );
  544. }
  545. return $indexes;
  546. }
  547. // returns true or false
  548. //
  549. // examples:
  550. // $db->Connect("host=host1 user=user1 password=secret port=4341");
  551. // $db->Connect('host1','user1','secret');
  552. function _connect($str,$user='',$pwd='',$db='',$ctype=0)
  553. {
  554. if (!function_exists('pg_connect')) return null;
  555. $this->_errorMsg = false;
  556. if ($user || $pwd || $db) {
  557. $user = adodb_addslashes($user);
  558. $pwd = adodb_addslashes($pwd);
  559. if (strlen($db) == 0) $db = 'template1';
  560. $db = adodb_addslashes($db);
  561. if ($str) {
  562. $host = split(":", $str);
  563. if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
  564. else $str = '';
  565. if (isset($host[1])) $str .= " port=$host[1]";
  566. else if (!empty($this->port)) $str .= " port=".$this->port;
  567. }
  568. if ($user) $str .= " user=".$user;
  569. if ($pwd) $str .= " password=".$pwd;
  570. if ($db) $str .= " dbname=".$db;
  571. }
  572. //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
  573. if ($ctype === 1) { // persistent
  574. $this->_connectionID = pg_pconnect($str);
  575. } else {
  576. if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str
  577. static $ncnt;
  578. if (empty($ncnt)) $ncnt = 1;
  579. else $ncnt += 1;
  580. $str .= str_repeat(' ',$ncnt);
  581. }
  582. $this->_connectionID = pg_connect($str);
  583. }
  584. if ($this->_connectionID === false) return false;
  585. $this->Execute("set datestyle='ISO'");
  586. $info = $this->ServerInfo();
  587. $this->pgVersion = (float) substr($info['version'],0,3);
  588. if ($this->pgVersion >= 7.1) { // good till version 999
  589. $this->_nestedSQL = true;
  590. }
  591. return true;
  592. }
  593. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  594. {
  595. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
  596. }
  597. // returns true or false
  598. //
  599. // examples:
  600. // $db->PConnect("host=host1 user=user1 password=secret port=4341");
  601. // $db->PConnect('host1','user1','secret');
  602. function _pconnect($str,$user='',$pwd='',$db='')
  603. {
  604. return $this->_connect($str,$user,$pwd,$db,1);
  605. }
  606. // returns queryID or false
  607. function _query($sql,$inputarr)
  608. {
  609. $this->_errorMsg = false;
  610. if ($inputarr) {
  611. /*
  612. It appears that PREPARE/EXECUTE is slower for many queries.
  613. For query executed 1000 times:
  614. "select id,firstname,lastname from adoxyz
  615. where firstname not like ? and lastname not like ? and id = ?"
  616. with plan = 1.51861286163 secs
  617. no plan = 1.26903700829 secs
  618. */
  619. $plan = 'P'.md5($sql);
  620. $execp = '';
  621. foreach($inputarr as $v) {
  622. if ($execp) $execp .= ',';
  623. if (is_string($v)) {
  624. if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
  625. } else {
  626. $execp .= $v;
  627. }
  628. }
  629. if ($execp) $exsql = "EXECUTE $plan ($execp)";
  630. else $exsql = "EXECUTE $plan";
  631. $rez = @pg_exec($this->_connectionID,$exsql);
  632. if (!$rez) {
  633. # Perhaps plan does not exist? Prepare/compile plan.
  634. $params = '';
  635. foreach($inputarr as $v) {
  636. if ($params) $params .= ',';
  637. if (is_string($v)) {
  638. $params .= 'VARCHAR';
  639. } else if (is_integer($v)) {
  640. $params .= 'INTEGER';
  641. } else {
  642. $params .= "REAL";
  643. }
  644. }
  645. $sqlarr = explode('?',$sql);
  646. //print_r($sqlarr);
  647. $sql = '';
  648. $i = 1;
  649. foreach($sqlarr as $v) {
  650. $sql .= $v.' $'.$i;
  651. $i++;
  652. }
  653. $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);
  654. //adodb_pr($s);
  655. $rez = pg_exec($this->_connectionID,$s);
  656. //echo $this->ErrorMsg();
  657. }
  658. if ($rez)
  659. $rez = pg_exec($this->_connectionID,$exsql);
  660. } else {
  661. //adodb_backtrace();
  662. $rez = pg_exec($this->_connectionID,$sql);
  663. }
  664. // check if no data returned, then no need to create real recordset
  665. if ($rez && pg_numfields($rez) <= 0) {
  666. if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
  667. pg_freeresult($this->_resultid);
  668. }
  669. $this->_resultid = $rez;
  670. return true;
  671. }
  672. return $rez;
  673. }
  674. function _errconnect()
  675. {
  676. if (defined('DB_ERROR_CONNECT_FAILED')) return DB_ERROR_CONNECT_FAILED;
  677. else return 'Database connection failed';
  678. }
  679. /* Returns: the last error message from previous database operation */
  680. function ErrorMsg()
  681. {
  682. if ($this->_errorMsg !== false) return $this->_errorMsg;
  683. if (ADODB_PHPVER >= 0x4300) {
  684. if (!empty($this->_resultid)) {
  685. $this->_errorMsg = @pg_result_error($this->_resultid);
  686. if ($this->_errorMsg) return $this->_errorMsg;
  687. }
  688. if (!empty($this->_connectionID)) {
  689. $this->_errorMsg = @pg_last_error($this->_connectionID);
  690. } else $this->_errorMsg = $this->_errconnect();
  691. } else {
  692. if (empty($this->_connectionID)) $this->_errconnect();
  693. else $this->_errorMsg = @pg_errormessage($this->_connectionID);
  694. }
  695. return $this->_errorMsg;
  696. }
  697. function ErrorNo()
  698. {
  699. $e = $this->ErrorMsg();
  700. if (strlen($e)) {
  701. return ADOConnection::MetaError($e);
  702. }
  703. return 0;
  704. }
  705. // returns true or false
  706. function _close()
  707. {
  708. if ($this->transCnt) $this->RollbackTrans();
  709. if ($this->_resultid) {
  710. @pg_freeresult($this->_resultid);
  711. $this->_resultid = false;
  712. }
  713. @pg_close($this->_connectionID);
  714. $this->_connectionID = false;
  715. return true;
  716. }
  717. /*
  718. * Maximum size of C field
  719. */
  720. function CharMax()
  721. {
  722. return 1000000000; // should be 1 Gb?
  723. }
  724. /*
  725. * Maximum size of X field
  726. */
  727. function TextMax()
  728. {
  729. return 1000000000; // should be 1 Gb?
  730. }
  731. }
  732. /*--------------------------------------------------------------------------------------
  733. Class Name: Recordset
  734. --------------------------------------------------------------------------------------*/
  735. class ADORecordSet_postgres64 extends ADORecordSet{
  736. var $_blobArr;
  737. var $databaseType = "postgres64";
  738. var $canSeek = true;
  739. function ADORecordSet_postgres64($queryID,$mode=false)
  740. {
  741. if ($mode === false) {
  742. global $ADODB_FETCH_MODE;
  743. $mode = $ADODB_FETCH_MODE;
  744. }
  745. switch ($mode)
  746. {
  747. case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
  748. case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
  749. case ADODB_FETCH_DEFAULT:
  750. case ADODB_FETCH_BOTH:
  751. default: $this->fetchMode = PGSQL_BOTH; break;
  752. }
  753. $this->adodbFetchMode = $mode;
  754. $this->ADORecordSet($queryID);
  755. }
  756. function GetRowAssoc($upper=true)
  757. {
  758. if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
  759. $row = ADORecordSet::GetRowAssoc($upper);
  760. return $row;
  761. }
  762. function _initrs()
  763. {
  764. global $ADODB_COUNTRECS;
  765. $qid = $this->_queryID;
  766. $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1;
  767. $this->_numOfFields = @pg_numfields($qid);
  768. // cache types for blob decode check
  769. // apparently pg_fieldtype actually performs an sql query on the database to get the type.
  770. if (empty($this->connection->noBlobs))
  771. for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
  772. if (pg_fieldtype($qid,$i) == 'bytea') {
  773. $this->_blobArr[$i] = pg_fieldname($qid,$i);
  774. }
  775. }
  776. }
  777. /* Use associative array to get fields array */
  778. function Fields($colname)
  779. {
  780. if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];
  781. if (!$this->bind) {
  782. $this->bind = array();
  783. for ($i=0; $i < $this->_numOfFields; $i++) {
  784. $o = $this->FetchField($i);
  785. $this->bind[strtoupper($o->name)] = $i;
  786. }
  787. }
  788. return $this->fields[$this->bind[strtoupper($colname)]];
  789. }
  790. function FetchField($off = 0)
  791. {
  792. // offsets begin at 0
  793. $o= new ADOFieldObject();
  794. $o->name = @pg_fieldname($this->_queryID,$off);
  795. $o->type = @pg_fieldtype($this->_queryID,$off);
  796. $o->max_length = @pg_fieldsize($this->_queryID,$off);
  797. return $o;
  798. }
  799. function _seek($row)
  800. {
  801. return @pg_fetch_row($this->_queryID,$row);
  802. }
  803. function _decode($blob)
  804. {
  805. eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
  806. return $realblob;
  807. }
  808. function _fixblobs()
  809. {
  810. if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
  811. foreach($this->_blobArr as $k => $v) {
  812. $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
  813. }
  814. }
  815. if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
  816. foreach($this->_blobArr as $k => $v) {
  817. $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
  818. }
  819. }
  820. }
  821. // 10% speedup to move MoveNext to child class
  822. function MoveNext()
  823. {
  824. if (!$this->EOF) {
  825. $this->_currentRow++;
  826. if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
  827. $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  828. if (is_array($this->fields) && $this->fields) {
  829. if (isset($this->_blobArr)) $this->_fixblobs();
  830. return true;
  831. }
  832. }
  833. $this->fields = false;
  834. $this->EOF = true;
  835. }
  836. return false;
  837. }
  838. function _fetch()
  839. {
  840. if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
  841. return false;
  842. $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  843. if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
  844. return (is_array($this->fields));
  845. }
  846. function _close()
  847. {
  848. return @pg_freeresult($this->_queryID);
  849. }
  850. function MetaType($t,$len=-1,$fieldobj=false)
  851. {
  852. if (is_object($t)) {
  853. $fieldobj = $t;
  854. $t = $fieldobj->type;
  855. $len = $fieldobj->max_length;
  856. }
  857. switch (strtoupper($t)) {
  858. case 'MONEY': // stupid, postgres expects money to be a string
  859. case 'INTERVAL':
  860. case 'CHAR':
  861. case 'CHARACTER':
  862. case 'VARCHAR':
  863. case 'NAME':
  864. case 'BPCHAR':
  865. case '_VARCHAR':
  866. case 'INET':
  867. case 'MACADDR':
  868. if ($len <= $this->blobSize) return 'C';
  869. case 'TEXT':
  870. return 'X';
  871. case 'IMAGE': // user defined type
  872. case 'BLOB': // user defined type
  873. case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
  874. case 'VARBIT':
  875. case 'BYTEA':
  876. return 'B';
  877. case 'BOOL':
  878. case 'BOOLEAN':
  879. return 'L';
  880. case 'DATE':
  881. return 'D';
  882. case 'TIMESTAMP WITHOUT TIME ZONE':
  883. case 'TIME':
  884. case 'DATETIME':
  885. case 'TIMESTAMP':
  886. case 'TIMESTAMPTZ':
  887. return 'T';
  888. case 'SMALLINT':
  889. case 'BIGINT':
  890. case 'INTEGER':
  891. case 'INT8':
  892. case 'INT4':
  893. case 'INT2':
  894. if (isset($fieldobj) &&
  895. empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
  896. case 'OID':
  897. case 'SERIAL':
  898. return 'R';
  899. default:
  900. return 'N';
  901. }
  902. }
  903. }
  904. ?>