PageRenderTime 51ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ext/adodb_5.18a/drivers/adodb-postgres64.inc.php

https://bitbucket.org/pontikis/tolc
PHP | 1078 lines | 905 code | 69 blank | 104 comment | 92 complexity | f9e958ab205a974bb8d0ac17035a99d8 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /*
  3. V5.18 3 Sep 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). 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 $uniqueIisR = true;
  95. var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
  96. var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
  97. var $_pnum = 0;
  98. // The last (fmtTimeStamp is not entirely correct:
  99. // PostgreSQL also has support for time zones,
  100. // and writes these time in this format: "2001-03-01 18:59:26+02".
  101. // There is no code for the "+02" time zone information, so I just left that out.
  102. // I'm not familiar enough with both ADODB as well as Postgres
  103. // to know what the concequences are. The other values are correct (wheren't in 0.94)
  104. // -- Freek Dijkstra
  105. function ADODB_postgres64()
  106. {
  107. // changes the metaColumnsSQL, adds columns: attnum[6]
  108. }
  109. function ServerInfo()
  110. {
  111. if (isset($this->version)) return $this->version;
  112. $arr['description'] = $this->GetOne("select version()");
  113. $arr['version'] = ADOConnection::_findvers($arr['description']);
  114. $this->version = $arr;
  115. return $arr;
  116. }
  117. function IfNull( $field, $ifNull )
  118. {
  119. return " coalesce($field, $ifNull) ";
  120. }
  121. // get the last id - never tested
  122. function pg_insert_id($tablename,$fieldname)
  123. {
  124. $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
  125. if ($result) {
  126. $arr = @pg_fetch_row($result,0);
  127. pg_freeresult($result);
  128. if (isset($arr[0])) return $arr[0];
  129. }
  130. return false;
  131. }
  132. /* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
  133. Using a OID as a unique identifier is not generally wise.
  134. Unless you are very careful, you might end up with a tuple having
  135. a different OID if a database must be reloaded. */
  136. function _insertid($table,$column)
  137. {
  138. if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
  139. $oid = pg_getlastoid($this->_resultid);
  140. // to really return the id, we need the table and column-name, else we can only return the oid != id
  141. return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT $column FROM $table WHERE oid=".(int)$oid);
  142. }
  143. // I get this error with PHP before 4.0.6 - jlim
  144. // Warning: This compilation does not support pg_cmdtuples() in adodb-postgres.inc.php on line 44
  145. function _affectedrows()
  146. {
  147. if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
  148. return pg_cmdtuples($this->_resultid);
  149. }
  150. // returns true/false
  151. function BeginTrans()
  152. {
  153. if ($this->transOff) return true;
  154. $this->transCnt += 1;
  155. return @pg_Exec($this->_connectionID, "begin ".$this->_transmode);
  156. }
  157. function RowLock($tables,$where,$col='1 as adodbignore')
  158. {
  159. if (!$this->transCnt) $this->BeginTrans();
  160. return $this->GetOne("select $col from $tables where $where for update");
  161. }
  162. // returns true/false.
  163. function CommitTrans($ok=true)
  164. {
  165. if ($this->transOff) return true;
  166. if (!$ok) return $this->RollbackTrans();
  167. $this->transCnt -= 1;
  168. return @pg_Exec($this->_connectionID, "commit");
  169. }
  170. // returns true/false
  171. function RollbackTrans()
  172. {
  173. if ($this->transOff) return true;
  174. $this->transCnt -= 1;
  175. return @pg_Exec($this->_connectionID, "rollback");
  176. }
  177. function MetaTables($ttype=false,$showSchema=false,$mask=false)
  178. {
  179. $info = $this->ServerInfo();
  180. if ($info['version'] >= 7.3) {
  181. $this->metaTablesSQL = "select table_name,'T' from information_schema.tables where table_schema not in ( 'pg_catalog','information_schema')
  182. union
  183. select table_name,'V' from information_schema.views where table_schema not in ( 'pg_catalog','information_schema') ";
  184. }
  185. if ($mask) {
  186. $save = $this->metaTablesSQL;
  187. $mask = $this->qstr(strtolower($mask));
  188. if ($info['version']>=7.3)
  189. $this->metaTablesSQL = "select table_name,'T' from information_schema.tables where table_name like $mask and table_schema not in ( 'pg_catalog','information_schema')
  190. union
  191. select table_name,'V' from information_schema.views where table_name like $mask and table_schema 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 (is_bool($s)) return $s ? 'true' : 'false';
  208. if (!$magic_quotes) {
  209. if (ADODB_PHPVER >= 0x5200 && $this->_connectionID) {
  210. return "'".pg_escape_string($this->_connectionID,$s)."'";
  211. }
  212. if (ADODB_PHPVER >= 0x4200) {
  213. return "'".pg_escape_string($s)."'";
  214. }
  215. if ($this->replaceQuote[0] == '\\'){
  216. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\\000"),$s);
  217. }
  218. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  219. }
  220. // undo magic quotes for "
  221. $s = str_replace('\\"','"',$s);
  222. return "'$s'";
  223. }
  224. // Format date column in sql string given an input format that understands Y M D
  225. function SQLDate($fmt, $col=false)
  226. {
  227. if (!$col) $col = $this->sysTimeStamp;
  228. $s = 'TO_CHAR('.$col.",'";
  229. $len = strlen($fmt);
  230. for ($i=0; $i < $len; $i++) {
  231. $ch = $fmt[$i];
  232. switch($ch) {
  233. case 'Y':
  234. case 'y':
  235. $s .= 'YYYY';
  236. break;
  237. case 'Q':
  238. case 'q':
  239. $s .= 'Q';
  240. break;
  241. case 'M':
  242. $s .= 'Mon';
  243. break;
  244. case 'm':
  245. $s .= 'MM';
  246. break;
  247. case 'D':
  248. case 'd':
  249. $s .= 'DD';
  250. break;
  251. case 'H':
  252. $s.= 'HH24';
  253. break;
  254. case 'h':
  255. $s .= 'HH';
  256. break;
  257. case 'i':
  258. $s .= 'MI';
  259. break;
  260. case 's':
  261. $s .= 'SS';
  262. break;
  263. case 'a':
  264. case 'A':
  265. $s .= 'AM';
  266. break;
  267. case 'w':
  268. $s .= 'D';
  269. break;
  270. case 'l':
  271. $s .= 'DAY';
  272. break;
  273. case 'W':
  274. $s .= 'WW';
  275. break;
  276. default:
  277. // handle escape characters...
  278. if ($ch == '\\') {
  279. $i++;
  280. $ch = substr($fmt,$i,1);
  281. }
  282. if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
  283. else $s .= '"'.$ch.'"';
  284. }
  285. }
  286. return $s. "')";
  287. }
  288. /*
  289. * Load a Large Object from a file
  290. * - the procedure stores the object id in the table and imports the object using
  291. * postgres proprietary blob handling routines
  292. *
  293. * contributed by Mattia Rossi mattia@technologist.com
  294. * modified for safe mode by juraj chlebec
  295. */
  296. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  297. {
  298. pg_exec ($this->_connectionID, "begin");
  299. $fd = fopen($path,'r');
  300. $contents = fread($fd,filesize($path));
  301. fclose($fd);
  302. $oid = pg_lo_create($this->_connectionID);
  303. $handle = pg_lo_open($this->_connectionID, $oid, 'w');
  304. pg_lo_write($handle, $contents);
  305. pg_lo_close($handle);
  306. // $oid = pg_lo_import ($path);
  307. pg_exec($this->_connectionID, "commit");
  308. $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype);
  309. $rez = !empty($rs);
  310. return $rez;
  311. }
  312. /*
  313. * Deletes/Unlinks a Blob from the database, otherwise it
  314. * will be left behind
  315. *
  316. * Returns TRUE on success or FALSE on failure.
  317. *
  318. * contributed by Todd Rogers todd#windfox.net
  319. */
  320. function BlobDelete( $blob )
  321. {
  322. pg_exec ($this->_connectionID, "begin");
  323. $result = @pg_lo_unlink($blob);
  324. pg_exec ($this->_connectionID, "commit");
  325. return( $result );
  326. }
  327. /*
  328. Hueristic - not guaranteed to work.
  329. */
  330. function GuessOID($oid)
  331. {
  332. if (strlen($oid)>16) return false;
  333. return is_numeric($oid);
  334. }
  335. /*
  336. * If an OID is detected, then we use pg_lo_* to open the oid file and read the
  337. * real blob from the db using the oid supplied as a parameter. If you are storing
  338. * blobs using bytea, we autodetect and process it so this function is not needed.
  339. *
  340. * contributed by Mattia Rossi mattia@technologist.com
  341. *
  342. * see http://www.postgresql.org/idocs/index.php?largeobjects.html
  343. *
  344. * Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
  345. * added maxsize parameter, which defaults to $db->maxblobsize if not defined.
  346. */
  347. function BlobDecode($blob,$maxsize=false,$hastrans=true)
  348. {
  349. if (!$this->GuessOID($blob)) return $blob;
  350. if ($hastrans) @pg_exec($this->_connectionID,"begin");
  351. $fd = @pg_lo_open($this->_connectionID,$blob,"r");
  352. if ($fd === false) {
  353. if ($hastrans) @pg_exec($this->_connectionID,"commit");
  354. return $blob;
  355. }
  356. if (!$maxsize) $maxsize = $this->maxblobsize;
  357. $realblob = @pg_loread($fd,$maxsize);
  358. @pg_loclose($fd);
  359. if ($hastrans) @pg_exec($this->_connectionID,"commit");
  360. return $realblob;
  361. }
  362. /*
  363. See http://www.postgresql.org/idocs/index.php?datatype-binary.html
  364. NOTE: SQL string literals (input strings) must be preceded with two backslashes
  365. due to the fact that they must pass through two parsers in the PostgreSQL
  366. backend.
  367. */
  368. function BlobEncode($blob)
  369. {
  370. if (ADODB_PHPVER >= 0x5200) return pg_escape_bytea($this->_connectionID, $blob);
  371. if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
  372. /*92=backslash, 0=null, 39=single-quote*/
  373. $badch = array(chr(92),chr(0),chr(39)); # \ null '
  374. $fixch = array('\\\\134','\\\\000','\\\\047');
  375. return adodb_str_replace($badch,$fixch,$blob);
  376. // note that there is a pg_escape_bytea function only for php 4.2.0 or later
  377. }
  378. // assumes bytea for blob, and varchar for clob
  379. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  380. {
  381. if ($blobtype == 'CLOB') {
  382. return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
  383. }
  384. // do not use bind params which uses qstr(), as blobencode() already quotes data
  385. return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
  386. }
  387. function OffsetDate($dayFraction,$date=false)
  388. {
  389. if (!$date) $date = $this->sysDate;
  390. else if (strncmp($date,"'",1) == 0) {
  391. $len = strlen($date);
  392. if (10 <= $len && $len <= 12) $date = 'date '.$date;
  393. else $date = 'timestamp '.$date;
  394. }
  395. return "($date+interval'".($dayFraction * 1440)." minutes')";
  396. #return "($date+interval'$dayFraction days')";
  397. }
  398. // for schema support, pass in the $table param "$schema.$tabname".
  399. // converts field names to lowercase, $upper is ignored
  400. // see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info
  401. function MetaColumns($table,$normalize=true)
  402. {
  403. global $ADODB_FETCH_MODE;
  404. $schema = false;
  405. $false = false;
  406. $this->_findschema($table,$schema);
  407. if ($normalize) $table = strtolower($table);
  408. $save = $ADODB_FETCH_MODE;
  409. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  410. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  411. if ($schema) $rs = $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
  412. else $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table,$table,$table));
  413. if (isset($savem)) $this->SetFetchMode($savem);
  414. $ADODB_FETCH_MODE = $save;
  415. if ($rs === false) {
  416. return $false;
  417. }
  418. if (!empty($this->metaKeySQL)) {
  419. // If we want the primary keys, we have to issue a separate query
  420. // Of course, a modified version of the metaColumnsSQL query using a
  421. // LEFT JOIN would have been much more elegant, but postgres does
  422. // not support OUTER JOINS. So here is the clumsy way.
  423. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  424. $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
  425. // fetch all result in once for performance.
  426. $keys = $rskey->GetArray();
  427. if (isset($savem)) $this->SetFetchMode($savem);
  428. $ADODB_FETCH_MODE = $save;
  429. $rskey->Close();
  430. unset($rskey);
  431. }
  432. $rsdefa = array();
  433. if (!empty($this->metaDefaultsSQL)) {
  434. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  435. $sql = sprintf($this->metaDefaultsSQL, ($table));
  436. $rsdef = $this->Execute($sql);
  437. if (isset($savem)) $this->SetFetchMode($savem);
  438. $ADODB_FETCH_MODE = $save;
  439. if ($rsdef) {
  440. while (!$rsdef->EOF) {
  441. $num = $rsdef->fields['num'];
  442. $s = $rsdef->fields['def'];
  443. if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
  444. $s = substr($s, 1);
  445. $s = substr($s, 0, strlen($s) - 1);
  446. }
  447. $rsdefa[$num] = $s;
  448. $rsdef->MoveNext();
  449. }
  450. } else {
  451. ADOConnection::outp( "==> SQL => " . $sql);
  452. }
  453. unset($rsdef);
  454. }
  455. $retarr = array();
  456. while (!$rs->EOF) {
  457. $fld = new ADOFieldObject();
  458. $fld->name = $rs->fields[0];
  459. $fld->type = $rs->fields[1];
  460. $fld->max_length = $rs->fields[2];
  461. $fld->attnum = $rs->fields[6];
  462. if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
  463. if ($fld->max_length <= 0) $fld->max_length = -1;
  464. if ($fld->type == 'numeric') {
  465. $fld->scale = $fld->max_length & 0xFFFF;
  466. $fld->max_length >>= 16;
  467. }
  468. // dannym
  469. // 5 hasdefault; 6 num-of-column
  470. $fld->has_default = ($rs->fields[5] == 't');
  471. if ($fld->has_default) {
  472. $fld->default_value = $rsdefa[$rs->fields[6]];
  473. }
  474. //Freek
  475. $fld->not_null = $rs->fields[4] == 't';
  476. // Freek
  477. if (is_array($keys)) {
  478. foreach($keys as $key) {
  479. if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't')
  480. $fld->primary_key = true;
  481. if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't')
  482. $fld->unique = true; // What name is more compatible?
  483. }
  484. }
  485. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  486. else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
  487. $rs->MoveNext();
  488. }
  489. $rs->Close();
  490. if (empty($retarr))
  491. return $false;
  492. else
  493. return $retarr;
  494. }
  495. function Param($name,$type='C')
  496. {
  497. $this->_pnum += 1;
  498. return '$'.$this->_pnum;
  499. }
  500. function MetaIndexes ($table, $primary = FALSE, $owner = 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 = explode(":", $str);
  570. if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
  571. else $str = '';
  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. $info = $this->ServerInfo();
  594. $this->pgVersion = (float) substr($info['version'],0,3);
  595. if ($this->pgVersion >= 7.1) { // good till version 999
  596. $this->_nestedSQL = true;
  597. }
  598. return true;
  599. }
  600. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  601. {
  602. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
  603. }
  604. // returns true or false
  605. //
  606. // examples:
  607. // $db->PConnect("host=host1 user=user1 password=secret port=4341");
  608. // $db->PConnect('host1','user1','secret');
  609. function _pconnect($str,$user='',$pwd='',$db='')
  610. {
  611. return $this->_connect($str,$user,$pwd,$db,1);
  612. }
  613. // returns queryID or false
  614. function _query($sql,$inputarr=false)
  615. {
  616. $this->_pnum = 0;
  617. $this->_errorMsg = false;
  618. if ($inputarr) {
  619. /*
  620. It appears that PREPARE/EXECUTE is slower for many queries.
  621. For query executed 1000 times:
  622. "select id,firstname,lastname from adoxyz
  623. where firstname not like ? and lastname not like ? and id = ?"
  624. with plan = 1.51861286163 secs
  625. no plan = 1.26903700829 secs
  626. */
  627. $plan = 'P'.md5($sql);
  628. $execp = '';
  629. foreach($inputarr as $v) {
  630. if ($execp) $execp .= ',';
  631. if (is_string($v)) {
  632. if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
  633. } else {
  634. $execp .= $v;
  635. }
  636. }
  637. if ($execp) $exsql = "EXECUTE $plan ($execp)";
  638. else $exsql = "EXECUTE $plan";
  639. $rez = @pg_exec($this->_connectionID,$exsql);
  640. if (!$rez) {
  641. # Perhaps plan does not exist? Prepare/compile plan.
  642. $params = '';
  643. foreach($inputarr as $v) {
  644. if ($params) $params .= ',';
  645. if (is_string($v)) {
  646. $params .= 'VARCHAR';
  647. } else if (is_integer($v)) {
  648. $params .= 'INTEGER';
  649. } else {
  650. $params .= "REAL";
  651. }
  652. }
  653. $sqlarr = explode('?',$sql);
  654. //print_r($sqlarr);
  655. $sql = '';
  656. $i = 1;
  657. foreach($sqlarr as $v) {
  658. $sql .= $v.' $'.$i;
  659. $i++;
  660. }
  661. $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);
  662. //adodb_pr($s);
  663. $rez = pg_exec($this->_connectionID,$s);
  664. //echo $this->ErrorMsg();
  665. }
  666. if ($rez)
  667. $rez = pg_exec($this->_connectionID,$exsql);
  668. } else {
  669. //adodb_backtrace();
  670. $rez = pg_exec($this->_connectionID,$sql);
  671. }
  672. // check if no data returned, then no need to create real recordset
  673. if ($rez && pg_numfields($rez) <= 0) {
  674. if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
  675. pg_freeresult($this->_resultid);
  676. }
  677. $this->_resultid = $rez;
  678. return true;
  679. }
  680. return $rez;
  681. }
  682. function _errconnect()
  683. {
  684. if (defined('DB_ERROR_CONNECT_FAILED')) return DB_ERROR_CONNECT_FAILED;
  685. else return 'Database connection failed';
  686. }
  687. /* Returns: the last error message from previous database operation */
  688. function ErrorMsg()
  689. {
  690. if ($this->_errorMsg !== false) return $this->_errorMsg;
  691. if (ADODB_PHPVER >= 0x4300) {
  692. if (!empty($this->_resultid)) {
  693. $this->_errorMsg = @pg_result_error($this->_resultid);
  694. if ($this->_errorMsg) return $this->_errorMsg;
  695. }
  696. if (!empty($this->_connectionID)) {
  697. $this->_errorMsg = @pg_last_error($this->_connectionID);
  698. } else $this->_errorMsg = $this->_errconnect();
  699. } else {
  700. if (empty($this->_connectionID)) $this->_errconnect();
  701. else $this->_errorMsg = @pg_errormessage($this->_connectionID);
  702. }
  703. return $this->_errorMsg;
  704. }
  705. function ErrorNo()
  706. {
  707. $e = $this->ErrorMsg();
  708. if (strlen($e)) {
  709. return ADOConnection::MetaError($e);
  710. }
  711. return 0;
  712. }
  713. // returns true or false
  714. function _close()
  715. {
  716. if ($this->transCnt) $this->RollbackTrans();
  717. if ($this->_resultid) {
  718. @pg_freeresult($this->_resultid);
  719. $this->_resultid = false;
  720. }
  721. @pg_close($this->_connectionID);
  722. $this->_connectionID = false;
  723. return true;
  724. }
  725. /*
  726. * Maximum size of C field
  727. */
  728. function CharMax()
  729. {
  730. return 1000000000; // should be 1 Gb?
  731. }
  732. /*
  733. * Maximum size of X field
  734. */
  735. function TextMax()
  736. {
  737. return 1000000000; // should be 1 Gb?
  738. }
  739. }
  740. /*--------------------------------------------------------------------------------------
  741. Class Name: Recordset
  742. --------------------------------------------------------------------------------------*/
  743. class ADORecordSet_postgres64 extends ADORecordSet{
  744. var $_blobArr;
  745. var $databaseType = "postgres64";
  746. var $canSeek = true;
  747. function ADORecordSet_postgres64($queryID,$mode=false)
  748. {
  749. if ($mode === false) {
  750. global $ADODB_FETCH_MODE;
  751. $mode = $ADODB_FETCH_MODE;
  752. }
  753. switch ($mode)
  754. {
  755. case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
  756. case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
  757. case ADODB_FETCH_DEFAULT:
  758. case ADODB_FETCH_BOTH:
  759. default: $this->fetchMode = PGSQL_BOTH; break;
  760. }
  761. $this->adodbFetchMode = $mode;
  762. $this->ADORecordSet($queryID);
  763. }
  764. function GetRowAssoc($upper=true)
  765. {
  766. if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
  767. $row = ADORecordSet::GetRowAssoc($upper);
  768. return $row;
  769. }
  770. function _initrs()
  771. {
  772. global $ADODB_COUNTRECS;
  773. $qid = $this->_queryID;
  774. $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1;
  775. $this->_numOfFields = @pg_numfields($qid);
  776. // cache types for blob decode check
  777. // apparently pg_fieldtype actually performs an sql query on the database to get the type.
  778. if (empty($this->connection->noBlobs))
  779. for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
  780. if (pg_fieldtype($qid,$i) == 'bytea') {
  781. $this->_blobArr[$i] = pg_fieldname($qid,$i);
  782. }
  783. }
  784. }
  785. /* Use associative array to get fields array */
  786. function Fields($colname)
  787. {
  788. if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];
  789. if (!$this->bind) {
  790. $this->bind = array();
  791. for ($i=0; $i < $this->_numOfFields; $i++) {
  792. $o = $this->FetchField($i);
  793. $this->bind[strtoupper($o->name)] = $i;
  794. }
  795. }
  796. return $this->fields[$this->bind[strtoupper($colname)]];
  797. }
  798. function FetchField($off = 0)
  799. {
  800. // offsets begin at 0
  801. $o= new ADOFieldObject();
  802. $o->name = @pg_fieldname($this->_queryID,$off);
  803. $o->type = @pg_fieldtype($this->_queryID,$off);
  804. $o->max_length = @pg_fieldsize($this->_queryID,$off);
  805. return $o;
  806. }
  807. function _seek($row)
  808. {
  809. return @pg_fetch_row($this->_queryID,$row);
  810. }
  811. function _decode($blob)
  812. {
  813. if ($blob === NULL) return NULL;
  814. // eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
  815. return pg_unescape_bytea($blob);
  816. }
  817. function _fixblobs()
  818. {
  819. if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
  820. foreach($this->_blobArr as $k => $v) {
  821. $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
  822. }
  823. }
  824. if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
  825. foreach($this->_blobArr as $k => $v) {
  826. $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
  827. }
  828. }
  829. }
  830. // 10% speedup to move MoveNext to child class
  831. function MoveNext()
  832. {
  833. if (!$this->EOF) {
  834. $this->_currentRow++;
  835. if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
  836. $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  837. if (is_array($this->fields) && $this->fields) {
  838. if (isset($this->_blobArr)) $this->_fixblobs();
  839. return true;
  840. }
  841. }
  842. $this->fields = false;
  843. $this->EOF = true;
  844. }
  845. return false;
  846. }
  847. function _fetch()
  848. {
  849. if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
  850. return false;
  851. $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  852. if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
  853. return (is_array($this->fields));
  854. }
  855. function _close()
  856. {
  857. return @pg_freeresult($this->_queryID);
  858. }
  859. function MetaType($t,$len=-1,$fieldobj=false)
  860. {
  861. if (is_object($t)) {
  862. $fieldobj = $t;
  863. $t = $fieldobj->type;
  864. $len = $fieldobj->max_length;
  865. }
  866. switch (strtoupper($t)) {
  867. case 'MONEY': // stupid, postgres expects money to be a string
  868. case 'INTERVAL':
  869. case 'CHAR':
  870. case 'CHARACTER':
  871. case 'VARCHAR':
  872. case 'NAME':
  873. case 'BPCHAR':
  874. case '_VARCHAR':
  875. case 'INET':
  876. case 'MACADDR':
  877. if ($len <= $this->blobSize) return 'C';
  878. case 'TEXT':
  879. return 'X';
  880. case 'IMAGE': // user defined type
  881. case 'BLOB': // user defined type
  882. case 'BIT': // This is a bit string, not a single bit, so don't return 'L'
  883. case 'VARBIT':
  884. case 'BYTEA':
  885. return 'B';
  886. case 'BOOL':
  887. case 'BOOLEAN':
  888. return 'L';
  889. case 'DATE':
  890. return 'D';
  891. case 'TIMESTAMP WITHOUT TIME ZONE':
  892. case 'TIME':
  893. case 'DATETIME':
  894. case 'TIMESTAMP':
  895. case 'TIMESTAMPTZ':
  896. return 'T';
  897. case 'SMALLINT':
  898. case 'BIGINT':
  899. case 'INTEGER':
  900. case 'INT8':
  901. case 'INT4':
  902. case 'INT2':
  903. if (isset($fieldobj) &&
  904. empty($fieldobj->primary_key) && (!$this->connection->uniqueIisR || empty($fieldobj->unique))) return 'I';
  905. case 'OID':
  906. case 'SERIAL':
  907. return 'R';
  908. default:
  909. return 'N';
  910. }
  911. }
  912. }
  913. ?>