adodb-postgres64.inc.php 31 KB

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