PageRenderTime 149ms CodeModel.GetById 37ms RepoModel.GetById 14ms app.codeStats 0ms

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

https://bitbucket.org/yousef_fadila/vtiger
PHP | 1066 lines | 896 code | 67 blank | 103 comment | 91 complexity | e1c9d13b3057f369bee9d5169c656f03 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. <?php
  2. /*
  3. V4.90 8 June 2006 (c) 2000-2006 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. function SetTransactionMode( $transaction_mode )
  149. {
  150. if (empty($transaction_mode)) {
  151. $transaction_mode = 'ISOLATION LEVEL SERIALIZABLE';
  152. }
  153. if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
  154. $this->_transmode = $transaction_mode;
  155. return( @pg_Exec($this->_connectionID, "SET SESSION TRANSACTION ".$transaction_mode));
  156. }
  157. function BeginTrans()
  158. {
  159. if ($this->transOff) return true;
  160. $this->transCnt += 1;
  161. if( $this->SetTransactionMode($this->_transmode))
  162. return @pg_Exec($this->_connectionID, "begin");
  163. else
  164. return(0);
  165. }
  166. function RowLock($tables,$where,$flds='1 as ignore')
  167. {
  168. if (!$this->transCnt) $this->BeginTrans();
  169. return $this->GetOne("select $flds from $tables where $where for update");
  170. }
  171. // returns true/false.
  172. function CommitTrans($ok=true)
  173. {
  174. if ($this->transOff) return true;
  175. if (!$ok) return $this->RollbackTrans();
  176. $this->transCnt -= 1;
  177. return @pg_Exec($this->_connectionID, "commit");
  178. }
  179. // returns true/false
  180. function RollbackTrans()
  181. {
  182. if ($this->transOff) return true;
  183. $this->transCnt -= 1;
  184. return @pg_Exec($this->_connectionID, "rollback");
  185. }
  186. function &MetaTables($ttype=false,$showSchema=false,$mask=false)
  187. {
  188. $info = $this->ServerInfo();
  189. if ($info['version'] >= 7.3) {
  190. $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
  191. and schemaname not in ( 'pg_catalog','information_schema')
  192. union
  193. select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') ";
  194. }
  195. if ($mask) {
  196. $save = $this->metaTablesSQL;
  197. $mask = $this->qstr(strtolower($mask));
  198. if ($info['version']>=7.3)
  199. $this->metaTablesSQL = "
  200. select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')
  201. union
  202. select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') ";
  203. else
  204. $this->metaTablesSQL = "
  205. select tablename,'T' from pg_tables where tablename like $mask
  206. union
  207. select viewname,'V' from pg_views where viewname like $mask";
  208. }
  209. $ret =& ADOConnection::MetaTables($ttype,$showSchema);
  210. if ($mask) {
  211. $this->metaTablesSQL = $save;
  212. }
  213. return $ret;
  214. }
  215. // if magic quotes disabled, use pg_escape_string()
  216. function qstr($s,$magic_quotes=false)
  217. {
  218. if (!$magic_quotes) {
  219. if (ADODB_PHPVER >= 0x4200) {
  220. return "'".pg_escape_string($s)."'";
  221. }
  222. if ($this->replaceQuote[0] == '\\'){
  223. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\\000"),$s);
  224. }
  225. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  226. }
  227. // undo magic quotes for "
  228. $s = str_replace('\\"','"',$s);
  229. return "'$s'";
  230. }
  231. // Format date column in sql string given an input format that understands Y M D
  232. function SQLDate($fmt, $col=false)
  233. {
  234. if (!$col) $col = $this->sysTimeStamp;
  235. $s = 'TO_CHAR('.$col.",'";
  236. $len = strlen($fmt);
  237. for ($i=0; $i < $len; $i++) {
  238. $ch = $fmt[$i];
  239. switch($ch) {
  240. case 'Y':
  241. case 'y':
  242. $s .= 'YYYY';
  243. break;
  244. case 'Q':
  245. case 'q':
  246. $s .= 'Q';
  247. break;
  248. case 'M':
  249. $s .= 'Mon';
  250. break;
  251. case 'm':
  252. $s .= 'MM';
  253. break;
  254. case 'D':
  255. case 'd':
  256. $s .= 'DD';
  257. break;
  258. case 'H':
  259. $s.= 'HH24';
  260. break;
  261. case 'h':
  262. $s .= 'HH';
  263. break;
  264. case 'i':
  265. $s .= 'MI';
  266. break;
  267. case 's':
  268. $s .= 'SS';
  269. break;
  270. case 'a':
  271. case 'A':
  272. $s .= 'AM';
  273. break;
  274. case 'w':
  275. $s .= 'D';
  276. break;
  277. case 'l':
  278. $s .= 'DAY';
  279. break;
  280. case 'W':
  281. $s .= 'WW';
  282. break;
  283. default:
  284. // handle escape characters...
  285. if ($ch == '\\') {
  286. $i++;
  287. $ch = substr($fmt,$i,1);
  288. }
  289. if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
  290. else $s .= '"'.$ch.'"';
  291. }
  292. }
  293. return $s. "')";
  294. }
  295. /*
  296. * Load a Large Object from a file
  297. * - the procedure stores the object id in the table and imports the object using
  298. * postgres proprietary blob handling routines
  299. *
  300. * contributed by Mattia Rossi mattia@technologist.com
  301. * modified for safe mode by juraj chlebec
  302. */
  303. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  304. {
  305. pg_exec ($this->_connectionID, "begin");
  306. $fd = fopen($path,'r');
  307. $contents = fread($fd,filesize($path));
  308. fclose($fd);
  309. $oid = pg_lo_create($this->_connectionID);
  310. $handle = pg_lo_open($this->_connectionID, $oid, 'w');
  311. pg_lo_write($handle, $contents);
  312. pg_lo_close($handle);
  313. // $oid = pg_lo_import ($path);
  314. pg_exec($this->_connectionID, "commit");
  315. $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype);
  316. $rez = !empty($rs);
  317. return $rez;
  318. }
  319. /*
  320. * Deletes/Unlinks a Blob from the database, otherwise it
  321. * will be left behind
  322. *
  323. * Returns TRUE on success or FALSE on failure.
  324. *
  325. * contributed by Todd Rogers todd#windfox.net
  326. */
  327. function BlobDelete( $blob )
  328. {
  329. pg_exec ($this->_connectionID, "begin");
  330. $result = @pg_lo_unlink($blob);
  331. pg_exec ($this->_connectionID, "commit");
  332. return( $result );
  333. }
  334. /*
  335. Hueristic - not guaranteed to work.
  336. */
  337. function GuessOID($oid)
  338. {
  339. if (strlen($oid)>16) return false;
  340. return is_numeric($oid);
  341. }
  342. /*
  343. * If an OID is detected, then we use pg_lo_* to open the oid file and read the
  344. * real blob from the db using the oid supplied as a parameter. If you are storing
  345. * blobs using bytea, we autodetect and process it so this function is not needed.
  346. *
  347. * contributed by Mattia Rossi mattia@technologist.com
  348. *
  349. * see http://www.postgresql.org/idocs/index.php?largeobjects.html
  350. *
  351. * Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
  352. * added maxsize parameter, which defaults to $db->maxblobsize if not defined.
  353. */
  354. function BlobDecode($blob,$maxsize=false,$hastrans=true)
  355. {
  356. if (!$this->GuessOID($blob)) return $blob;
  357. if ($hastrans) @pg_exec($this->_connectionID,"begin");
  358. $fd = @pg_lo_open($this->_connectionID,$blob,"r");
  359. if ($fd === false) {
  360. if ($hastrans) @pg_exec($this->_connectionID,"commit");
  361. return $blob;
  362. }
  363. if (!$maxsize) $maxsize = $this->maxblobsize;
  364. $realblob = @pg_loread($fd,$maxsize);
  365. @pg_loclose($fd);
  366. if ($hastrans) @pg_exec($this->_connectionID,"commit");
  367. return $realblob;
  368. }
  369. /*
  370. See http://www.postgresql.org/idocs/index.php?datatype-binary.html
  371. NOTE: SQL string literals (input strings) must be preceded with two backslashes
  372. due to the fact that they must pass through two parsers in the PostgreSQL
  373. backend.
  374. */
  375. function BlobEncode($blob)
  376. {
  377. if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
  378. /*92=backslash, 0=null, 39=single-quote*/
  379. $badch = array(chr(92),chr(0),chr(39)); # \ null '
  380. $fixch = array('\\\\134','\\\\000','\\\\047');
  381. return adodb_str_replace($badch,$fixch,$blob);
  382. // note that there is a pg_escape_bytea function only for php 4.2.0 or later
  383. }
  384. // assumes bytea for blob, and varchar for clob
  385. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  386. {
  387. if ($blobtype == 'CLOB') {
  388. return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
  389. }
  390. // do not use bind params which uses qstr(), as blobencode() already quotes data
  391. return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
  392. }
  393. function OffsetDate($dayFraction,$date=false)
  394. {
  395. if (!$date) $date = $this->sysDate;
  396. else if (strncmp($date,"'",1) == 0) {
  397. $len = strlen($date);
  398. if (10 <= $len && $len <= 12) $date = 'date '.$date;
  399. else $date = 'timestamp '.$date;
  400. }
  401. return "($date+interval'$dayFraction days')";
  402. }
  403. // for schema support, pass in the $table param "$schema.$tabname".
  404. // converts field names to lowercase, $upper is ignored
  405. // see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info
  406. function &MetaColumns($table,$normalize=true)
  407. {
  408. global $ADODB_FETCH_MODE;
  409. $schema = false;
  410. $false = false;
  411. $this->_findschema($table,$schema);
  412. if ($normalize) $table = strtolower($table);
  413. $save = $ADODB_FETCH_MODE;
  414. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  415. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  416. if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
  417. else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
  418. if (isset($savem)) $this->SetFetchMode($savem);
  419. $ADODB_FETCH_MODE = $save;
  420. if ($rs === false) {
  421. return $false;
  422. }
  423. if (!empty($this->metaKeySQL)) {
  424. // If we want the primary keys, we have to issue a separate query
  425. // Of course, a modified version of the metaColumnsSQL query using a
  426. // LEFT JOIN would have been much more elegant, but postgres does
  427. // not support OUTER JOINS. So here is the clumsy way.
  428. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  429. $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
  430. // fetch all result in once for performance.
  431. $keys =& $rskey->GetArray();
  432. if (isset($savem)) $this->SetFetchMode($savem);
  433. $ADODB_FETCH_MODE = $save;
  434. $rskey->Close();
  435. unset($rskey);
  436. }
  437. $rsdefa = array();
  438. if (!empty($this->metaDefaultsSQL)) {
  439. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  440. $sql = sprintf($this->metaDefaultsSQL, ($table));
  441. $rsdef = $this->Execute($sql);
  442. if (isset($savem)) $this->SetFetchMode($savem);
  443. $ADODB_FETCH_MODE = $save;
  444. if ($rsdef) {
  445. while (!$rsdef->EOF) {
  446. $num = $rsdef->fields['num'];
  447. $s = $rsdef->fields['def'];
  448. if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
  449. $s = substr($s, 1);
  450. $s = substr($s, 0, strlen($s) - 1);
  451. }
  452. $rsdefa[$num] = $s;
  453. $rsdef->MoveNext();
  454. }
  455. } else {
  456. ADOConnection::outp( "==> SQL => " . $sql);
  457. }
  458. unset($rsdef);
  459. }
  460. $retarr = array();
  461. while (!$rs->EOF) {
  462. $fld = new ADOFieldObject();
  463. $fld->name = $rs->fields[0];
  464. $fld->type = $rs->fields[1];
  465. $fld->max_length = $rs->fields[2];
  466. $fld->attnum = $rs->fields[6];
  467. if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
  468. if ($fld->max_length <= 0) $fld->max_length = -1;
  469. if ($fld->type == 'numeric') {
  470. $fld->scale = $fld->max_length & 0xFFFF;
  471. $fld->max_length >>= 16;
  472. }
  473. // dannym
  474. // 5 hasdefault; 6 num-of-column
  475. $fld->has_default = ($rs->fields[5] == 't');
  476. if ($fld->has_default) {
  477. $fld->default_value = $rsdefa[$rs->fields[6]];
  478. }
  479. //Freek
  480. $fld->not_null = $rs->fields[4] == 't';
  481. // Freek
  482. if (is_array($keys)) {
  483. foreach($keys as $key) {
  484. if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
  485. $fld->primary_key = true;
  486. if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
  487. $fld->unique = true; // What name is more compatible?
  488. }
  489. }
  490. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  491. else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
  492. $rs->MoveNext();
  493. }
  494. $rs->Close();
  495. if (empty($retarr))
  496. return $false;
  497. else
  498. return $retarr;
  499. }
  500. function &MetaIndexes ($table, $primary = FALSE)
  501. {
  502. global $ADODB_FETCH_MODE;
  503. $schema = false;
  504. $this->_findschema($table,$schema);
  505. if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
  506. $sql = '
  507. SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
  508. FROM pg_catalog.pg_class c
  509. JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
  510. JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
  511. ,pg_namespace n
  512. WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
  513. } else {
  514. $sql = '
  515. SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
  516. FROM pg_catalog.pg_class c
  517. JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
  518. JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
  519. WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
  520. }
  521. if ($primary == FALSE) {
  522. $sql .= ' AND i.indisprimary=false;';
  523. }
  524. $save = $ADODB_FETCH_MODE;
  525. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  526. if ($this->fetchMode !== FALSE) {
  527. $savem = $this->SetFetchMode(FALSE);
  528. }
  529. $rs = $this->Execute(sprintf($sql,$table,$table,$schema));
  530. if (isset($savem)) {
  531. $this->SetFetchMode($savem);
  532. }
  533. $ADODB_FETCH_MODE = $save;
  534. if (!is_object($rs)) {
  535. $false = false;
  536. return $false;
  537. }
  538. $col_names = $this->MetaColumnNames($table,true,true);
  539. //3rd param is use attnum,
  540. // see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
  541. $indexes = array();
  542. while ($row = $rs->FetchRow()) {
  543. $columns = array();
  544. foreach (explode(' ', $row[2]) as $col) {
  545. $columns[] = $col_names[$col];
  546. }
  547. $indexes[$row[0]] = array(
  548. 'unique' => ($row[1] == 't'),
  549. 'columns' => $columns
  550. );
  551. }
  552. return $indexes;
  553. }
  554. // returns true or false
  555. //
  556. // examples:
  557. // $db->Connect("host=host1 user=user1 password=secret port=4341");
  558. // $db->Connect('host1','user1','secret');
  559. function _connect($str,$user='',$pwd='',$db='',$ctype=0)
  560. {
  561. if (!function_exists('pg_connect')) return null;
  562. $this->_errorMsg = false;
  563. if ($user || $pwd || $db) {
  564. $user = adodb_addslashes($user);
  565. $pwd = adodb_addslashes($pwd);
  566. if (strlen($db) == 0) $db = 'template1';
  567. $db = adodb_addslashes($db);
  568. if ($str) {
  569. $host = split(":", $str);
  570. if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
  571. else $str = 'host=localhost';
  572. if (isset($host[1])) $str .= " port=$host[1]";
  573. else if (!empty($this->port)) $str .= " port=".$this->port;
  574. }
  575. if ($user) $str .= " user=".$user;
  576. if ($pwd) $str .= " password=".$pwd;
  577. if ($db) $str .= " dbname=".$db;
  578. }
  579. //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
  580. if ($ctype === 1) { // persistent
  581. $this->_connectionID = pg_pconnect($str);
  582. } else {
  583. if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str
  584. static $ncnt;
  585. if (empty($ncnt)) $ncnt = 1;
  586. else $ncnt += 1;
  587. $str .= str_repeat(' ',$ncnt);
  588. }
  589. $this->_connectionID = pg_connect($str);
  590. }
  591. if ($this->_connectionID === false) return false;
  592. $this->Execute("set datestyle='ISO'");
  593. return true;
  594. }
  595. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  596. {
  597. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
  598. }
  599. // returns true or false
  600. //
  601. // examples:
  602. // $db->PConnect("host=host1 user=user1 password=secret port=4341");
  603. // $db->PConnect('host1','user1','secret');
  604. function _pconnect($str,$user='',$pwd='',$db='')
  605. {
  606. return $this->_connect($str,$user,$pwd,$db,1);
  607. }
  608. // returns queryID or false
  609. function _query($sql,$inputarr)
  610. {
  611. $this->_errorMsg = false;
  612. if ($inputarr) {
  613. /*
  614. It appears that PREPARE/EXECUTE is slower for many queries.
  615. For query executed 1000 times:
  616. "select id,firstname,lastname from adoxyz
  617. where firstname not like ? and lastname not like ? and id = ?"
  618. with plan = 1.51861286163 secs
  619. no plan = 1.26903700829 secs
  620. */
  621. $plan = 'P'.md5($sql);
  622. $execp = '';
  623. foreach($inputarr as $v) {
  624. if ($execp) $execp .= ',';
  625. if (is_string($v)) {
  626. if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
  627. } else {
  628. $execp .= $v;
  629. }
  630. }
  631. if ($execp) $exsql = "EXECUTE $plan ($execp)";
  632. else $exsql = "EXECUTE $plan";
  633. $rez = @pg_exec($this->_connectionID,$exsql);
  634. if (!$rez) {
  635. # Perhaps plan does not exist? Prepare/compile plan.
  636. $params = '';
  637. foreach($inputarr as $v) {
  638. if ($params) $params .= ',';
  639. if (is_string($v)) {
  640. $params .= 'VARCHAR';
  641. } else if (is_integer($v)) {
  642. $params .= 'INTEGER';
  643. } else {
  644. $params .= "REAL";
  645. }
  646. }
  647. $sqlarr = explode('?',$sql);
  648. //print_r($sqlarr);
  649. $sql = '';
  650. $i = 1;
  651. foreach($sqlarr as $v) {
  652. $sql .= $v.' $'.$i;
  653. $i++;
  654. }
  655. $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);
  656. //adodb_pr($s);
  657. pg_exec($this->_connectionID,$s);
  658. //echo $this->ErrorMsg();
  659. }
  660. $rez = pg_exec($this->_connectionID,$exsql);
  661. } else {
  662. //adodb_backtrace();
  663. $rez = pg_exec($this->_connectionID,$sql);
  664. }
  665. // check if no data returned, then no need to create real recordset
  666. if ($rez && pg_numfields($rez) <= 0) {
  667. if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
  668. pg_freeresult($this->_resultid);
  669. }
  670. $this->_resultid = $rez;
  671. return true;
  672. }
  673. return $rez;
  674. }
  675. function _errconnect()
  676. {
  677. if (defined('DB_ERROR_CONNECT_FAILED')) return DB_ERROR_CONNECT_FAILED;
  678. else return 'Database connection failed';
  679. }
  680. /* Returns: the last error message from previous database operation */
  681. function ErrorMsg()
  682. {
  683. if ($this->_errorMsg !== false) return $this->_errorMsg;
  684. if (ADODB_PHPVER >= 0x4300) {
  685. if (!empty($this->_resultid)) {
  686. $this->_errorMsg = @pg_result_error($this->_resultid);
  687. if ($this->_errorMsg) return $this->_errorMsg;
  688. }
  689. if (!empty($this->_connectionID)) {
  690. $this->_errorMsg = @pg_last_error($this->_connectionID);
  691. } else $this->_errorMsg = $this->_errconnect();
  692. } else {
  693. if (empty($this->_connectionID)) $this->_errconnect();
  694. else $this->_errorMsg = @pg_errormessage($this->_connectionID);
  695. }
  696. return $this->_errorMsg;
  697. }
  698. function ErrorNo()
  699. {
  700. $e = $this->ErrorMsg();
  701. if (strlen($e)) {
  702. return ADOConnection::MetaError($e);
  703. }
  704. return 0;
  705. }
  706. // returns true or false
  707. function _close()
  708. {
  709. if ($this->transCnt) $this->RollbackTrans();
  710. if ($this->_resultid) {
  711. @pg_freeresult($this->_resultid);
  712. $this->_resultid = false;
  713. }
  714. @pg_close($this->_connectionID);
  715. $this->_connectionID = false;
  716. return true;
  717. }
  718. /*
  719. * Maximum size of C field
  720. */
  721. function CharMax()
  722. {
  723. return 1000000000; // should be 1 Gb?
  724. }
  725. /*
  726. * Maximum size of X field
  727. */
  728. function TextMax()
  729. {
  730. return 1000000000; // should be 1 Gb?
  731. }
  732. }
  733. /*--------------------------------------------------------------------------------------
  734. Class Name: Recordset
  735. --------------------------------------------------------------------------------------*/
  736. class ADORecordSet_postgres64 extends ADORecordSet{
  737. var $_blobArr;
  738. var $databaseType = "postgres64";
  739. var $canSeek = true;
  740. function ADORecordSet_postgres64($queryID,$mode=false)
  741. {
  742. if ($mode === false) {
  743. global $ADODB_FETCH_MODE;
  744. $mode = $ADODB_FETCH_MODE;
  745. }
  746. switch ($mode)
  747. {
  748. case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
  749. case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
  750. case ADODB_FETCH_DEFAULT:
  751. case ADODB_FETCH_BOTH:
  752. default: $this->fetchMode = PGSQL_BOTH; break;
  753. }
  754. $this->adodbFetchMode = $mode;
  755. $this->ADORecordSet($queryID);
  756. }
  757. function &GetRowAssoc($upper=true)
  758. {
  759. if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
  760. $row =& ADORecordSet::GetRowAssoc($upper);
  761. return $row;
  762. }
  763. function _initrs()
  764. {
  765. global $ADODB_COUNTRECS;
  766. $qid = $this->_queryID;
  767. $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1;
  768. $this->_numOfFields = @pg_numfields($qid);
  769. // cache types for blob decode check
  770. // apparently pg_fieldtype actually performs an sql query on the database to get the type.
  771. if (empty($this->connection->noBlobs))
  772. for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
  773. if (pg_fieldtype($qid,$i) == 'bytea') {
  774. $this->_blobArr[$i] = pg_fieldname($qid,$i);
  775. }
  776. }
  777. }
  778. /* Use associative array to get fields array */
  779. function Fields($colname)
  780. {
  781. if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];
  782. if (!$this->bind) {
  783. $this->bind = array();
  784. for ($i=0; $i < $this->_numOfFields; $i++) {
  785. $o = $this->FetchField($i);
  786. $this->bind[strtoupper($o->name)] = $i;
  787. }
  788. }
  789. return $this->fields[$this->bind[strtoupper($colname)]];
  790. }
  791. function &FetchField($off = 0)
  792. {
  793. // offsets begin at 0
  794. $o= new ADOFieldObject();
  795. $o->name = @pg_fieldname($this->_queryID,$off);
  796. $o->type = @pg_fieldtype($this->_queryID,$off);
  797. $o->max_length = @pg_fieldsize($this->_queryID,$off);
  798. return $o;
  799. }
  800. function _seek($row)
  801. {
  802. return @pg_fetch_row($this->_queryID,$row);
  803. }
  804. function _decode($blob)
  805. {
  806. eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
  807. return $realblob;
  808. }
  809. function _fixblobs()
  810. {
  811. if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
  812. foreach($this->_blobArr as $k => $v) {
  813. $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
  814. }
  815. }
  816. if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
  817. foreach($this->_blobArr as $k => $v) {
  818. $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
  819. }
  820. }
  821. }
  822. // 10% speedup to move MoveNext to child class
  823. function MoveNext()
  824. {
  825. if (!$this->EOF) {
  826. $this->_currentRow++;
  827. if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
  828. $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  829. if (is_array($this->fields) && $this->fields) {
  830. if (isset($this->_blobArr)) $this->_fixblobs();
  831. return true;
  832. }
  833. }
  834. $this->fields = false;
  835. $this->EOF = true;
  836. }
  837. return false;
  838. }
  839. function _fetch()
  840. {
  841. if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
  842. return false;
  843. $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  844. if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
  845. return (is_array($this->fields));
  846. }
  847. function _close()
  848. {
  849. return @pg_freeresult($this->_queryID);
  850. }
  851. function MetaType($t,$len=-1,$fieldobj=false)
  852. {
  853. if (is_object($t)) {
  854. $fieldobj = $t;
  855. $t = $fieldobj->type;
  856. $len = $fieldobj->max_length;
  857. }
  858. switch (strtoupper($t)) {
  859. case 'MONEY': // stupid, postgres expects money to be a string
  860. case 'INTERVAL':
  861. case 'CHAR':
  862. case 'CHARACTER':
  863. case 'VARCHAR':
  864. case 'NAME':
  865. case 'BPCHAR':
  866. case '_VARCHAR':
  867. case 'INET':
  868. case 'MACADDR':
  869. if ($len <= $this->blobSize) return 'C';
  870. case 'TEXT':
  871. return 'X';
  872. case 'IMAGE': // user defined type
  873. case 'BLOB': // user defined type
  874. case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
  875. case 'VARBIT':
  876. case 'BYTEA':
  877. return 'B';
  878. case 'BOOL':
  879. case 'BOOLEAN':
  880. return 'L';
  881. case 'DATE':
  882. return 'D';
  883. case 'TIMESTAMP WITHOUT TIME ZONE':
  884. case 'TIME':
  885. case 'DATETIME':
  886. case 'TIMESTAMP':
  887. case 'TIMESTAMPTZ':
  888. return 'T';
  889. case 'SMALLINT':
  890. case 'BIGINT':
  891. case 'INTEGER':
  892. case 'INT8':
  893. case 'INT4':
  894. case 'INT2':
  895. if (isset($fieldobj) &&
  896. empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
  897. case 'OID':
  898. case 'SERIAL':
  899. return 'R';
  900. default:
  901. return 'N';
  902. }
  903. }
  904. }
  905. ?>