pgsql.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * The PEAR DB driver for PHP's pgsql extension
  5. * for interacting with PostgreSQL databases
  6. *
  7. * PHP version 5
  8. *
  9. * LICENSE: This source file is subject to version 3.0 of the PHP license
  10. * that is available through the world-wide-web at the following URI:
  11. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  12. * the PHP License and are unable to obtain it through the web, please
  13. * send a note to license@php.net so we can mail you a copy immediately.
  14. *
  15. * @category Database
  16. * @package DB
  17. * @author Rui Hirokawa <hirokawa@php.net>
  18. * @author Stig Bakken <ssb@php.net>
  19. * @author Daniel Convissor <danielc@php.net>
  20. * @copyright 1997-2007 The PHP Group
  21. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  22. * @version CVS: $Id$
  23. * @link http://pear.php.net/package/DB
  24. */
  25. /**
  26. * Obtain the DB_common class so it can be extended from
  27. */
  28. //require_once 'DB/common.php';
  29. require_once 'common.php';
  30. /**
  31. * The methods PEAR DB uses to interact with PHP's pgsql extension
  32. * for interacting with PostgreSQL databases
  33. *
  34. * These methods overload the ones declared in DB_common.
  35. *
  36. * @category Database
  37. * @package DB
  38. * @author Rui Hirokawa <hirokawa@php.net>
  39. * @author Stig Bakken <ssb@php.net>
  40. * @author Daniel Convissor <danielc@php.net>
  41. * @copyright 1997-2007 The PHP Group
  42. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  43. * @version Release: 1.9.2
  44. * @link http://pear.php.net/package/DB
  45. */
  46. class DB_pgsql extends DB_common
  47. {
  48. // {{{ properties
  49. /**
  50. * The DB driver type (mysql, oci8, odbc, etc.)
  51. * @var string
  52. */
  53. public $phptype = 'pgsql';
  54. /**
  55. * The database syntax variant to be used (db2, access, etc.), if any
  56. * @var string
  57. */
  58. public $dbsyntax = 'pgsql';
  59. /**
  60. * The capabilities of this DB implementation
  61. *
  62. * The 'new_link' element contains the PHP version that first provided
  63. * new_link support for this DBMS. Contains false if it's unsupported.
  64. *
  65. * Meaning of the 'limit' element:
  66. * + 'emulate' = emulate with fetch row by number
  67. * + 'alter' = alter the query
  68. * + false = skip rows
  69. *
  70. * @var array
  71. */
  72. public $features = array(
  73. 'limit' => 'alter',
  74. 'new_link' => '4.3.0',
  75. 'numrows' => true,
  76. 'pconnect' => true,
  77. 'prepare' => false,
  78. 'ssl' => true,
  79. 'transactions' => true,
  80. );
  81. /**
  82. * A mapping of native error codes to DB error codes
  83. * @var array
  84. */
  85. public $errorcode_map = array();
  86. /**
  87. * The raw database connection created by PHP
  88. * @var resource
  89. */
  90. public $connection;
  91. /**
  92. * The DSN information for connecting to a database
  93. * @var array
  94. */
  95. public $dsn = array();
  96. /**
  97. * Should data manipulation queries be committed automatically?
  98. * @var bool
  99. * @access private
  100. */
  101. public $autocommit = true;
  102. /**
  103. * The quantity of transactions begun
  104. *
  105. * {@internal While this is private, it can't actually be designated
  106. * private in PHP 5 because it is directly accessed in the test suite.}}
  107. *
  108. * @var integer
  109. * @access private
  110. */
  111. public $transaction_opcount = 0;
  112. /**
  113. * The number of rows affected by a data manipulation query
  114. * @var integer
  115. */
  116. public $affected = 0;
  117. /**
  118. * The current row being looked at in fetchInto()
  119. * @var array
  120. * @access private
  121. */
  122. public $row = array();
  123. /**
  124. * The number of rows in a given result set
  125. * @var array
  126. * @access private
  127. */
  128. public $_num_rows = array();
  129. // }}}
  130. // {{{ constructor
  131. /**
  132. * This constructor calls <kbd>parent::__construct()</kbd>
  133. *
  134. * @return void
  135. */
  136. public function __construct()
  137. {
  138. parent::__construct();
  139. }
  140. // }}}
  141. // {{{ connect()
  142. /**
  143. * Connect to the database server, log in and open the database
  144. *
  145. * Don't call this method directly. Use DB::connect() instead.
  146. *
  147. * PEAR DB's pgsql driver supports the following extra DSN options:
  148. * + connect_timeout How many seconds to wait for a connection to
  149. * be established. Available since PEAR DB 1.7.0.
  150. * + new_link If set to true, causes subsequent calls to
  151. * connect() to return a new connection link
  152. * instead of the existing one. WARNING: this is
  153. * not portable to other DBMS's. Available only
  154. * if PHP is >= 4.3.0 and PEAR DB is >= 1.7.0.
  155. * + options Command line options to be sent to the server.
  156. * Available since PEAR DB 1.6.4.
  157. * + service Specifies a service name in pg_service.conf that
  158. * holds additional connection parameters.
  159. * Available since PEAR DB 1.7.0.
  160. * + sslmode How should SSL be used when connecting? Values:
  161. * disable, allow, prefer or require.
  162. * Available since PEAR DB 1.7.0.
  163. * + tty This was used to specify where to send server
  164. * debug output. Available since PEAR DB 1.6.4.
  165. *
  166. * Example of connecting to a new link via a socket:
  167. * <code>
  168. * require_once 'DB.php';
  169. *
  170. * $dsn = 'pgsql://user:pass@unix(/tmp)/dbname?new_link=true';
  171. * $options = array(
  172. * 'portability' => DB_PORTABILITY_ALL,
  173. * );
  174. *
  175. * $db = DB::connect($dsn, $options);
  176. * if ((new PEAR)->isError($db)) {
  177. * die($db->getMessage());
  178. * }
  179. * </code>
  180. *
  181. * @param array $dsn the data source name
  182. * @param bool $persistent should the connection be persistent?
  183. *
  184. * @return int|object
  185. *
  186. * @link http://www.postgresql.org/docs/current/static/libpq.html#LIBPQ-CONNECT
  187. */
  188. public function connect($dsn, $persistent = false)
  189. {
  190. if (!PEAR::loadExtension('pgsql')) {
  191. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  192. }
  193. $this->dsn = $dsn;
  194. if ($dsn['dbsyntax']) {
  195. $this->dbsyntax = $dsn['dbsyntax'];
  196. }
  197. $protocol = $dsn['protocol'] ? $dsn['protocol'] : 'tcp';
  198. $params = array('');
  199. if ($protocol == 'tcp') {
  200. if ($dsn['hostspec']) {
  201. $params[0] .= 'host=' . $dsn['hostspec'];
  202. }
  203. if ($dsn['port']) {
  204. $params[0] .= ' port=' . $dsn['port'];
  205. }
  206. } elseif ($protocol == 'unix') {
  207. // Allow for pg socket in non-standard locations.
  208. if ($dsn['socket']) {
  209. $params[0] .= 'host=' . $dsn['socket'];
  210. }
  211. if ($dsn['port']) {
  212. $params[0] .= ' port=' . $dsn['port'];
  213. }
  214. }
  215. if ($dsn['database']) {
  216. $params[0] .= ' dbname=\'' . addslashes($dsn['database']) . '\'';
  217. }
  218. if ($dsn['username']) {
  219. $params[0] .= ' user=\'' . addslashes($dsn['username']) . '\'';
  220. }
  221. if ($dsn['password']) {
  222. $params[0] .= ' password=\'' . addslashes($dsn['password']) . '\'';
  223. }
  224. if (!empty($dsn['options'])) {
  225. $params[0] .= ' options=' . $dsn['options'];
  226. }
  227. if (!empty($dsn['tty'])) {
  228. $params[0] .= ' tty=' . $dsn['tty'];
  229. }
  230. if (!empty($dsn['connect_timeout'])) {
  231. $params[0] .= ' connect_timeout=' . $dsn['connect_timeout'];
  232. }
  233. if (!empty($dsn['sslmode'])) {
  234. $params[0] .= ' sslmode=' . $dsn['sslmode'];
  235. }
  236. if (!empty($dsn['service'])) {
  237. $params[0] .= ' service=' . $dsn['service'];
  238. }
  239. if (isset($dsn['new_link'])
  240. && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true)) {
  241. if (version_compare(phpversion(), '4.3.0', '>=')) {
  242. $params[] = PGSQL_CONNECT_FORCE_NEW;
  243. }
  244. }
  245. $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
  246. $ini = ini_get('track_errors');
  247. $php_errormsg = '';
  248. if ($ini) {
  249. $this->connection = @call_user_func_array(
  250. $connect_function,
  251. $params
  252. );
  253. } else {
  254. @ini_set('track_errors', 1);
  255. $this->connection = @call_user_func_array(
  256. $connect_function,
  257. $params
  258. );
  259. @ini_set('track_errors', $ini);
  260. }
  261. if (!$this->connection) {
  262. return $this->raiseError(
  263. DB_ERROR_CONNECT_FAILED,
  264. null,
  265. null,
  266. null,
  267. $php_errormsg
  268. );
  269. }
  270. return DB_OK;
  271. }
  272. // }}}
  273. // {{{ disconnect()
  274. /**
  275. * Disconnects from the database server
  276. *
  277. * @return bool TRUE on success, FALSE on failure
  278. */
  279. public function disconnect()
  280. {
  281. $ret = @pg_close($this->connection);
  282. $this->connection = null;
  283. return $ret;
  284. }
  285. // }}}
  286. // {{{ simpleQuery()
  287. /**
  288. * Sends a query to the database server
  289. *
  290. * @param string the SQL query string
  291. *
  292. * @return mixed + a PHP result resrouce for successful SELECT queries
  293. * + the DB_OK constant for other successful queries
  294. * + a DB_Error object on failure
  295. */
  296. public function simpleQuery($query)
  297. {
  298. $ismanip = $this->_checkManip($query);
  299. $this->last_query = $query;
  300. $query = $this->modifyQuery($query);
  301. if (!$this->autocommit && $ismanip) {
  302. if ($this->transaction_opcount == 0) {
  303. $result = @pg_exec($this->connection, 'begin;');
  304. if (!$result) {
  305. return $this->pgsqlRaiseError();
  306. }
  307. }
  308. $this->transaction_opcount++;
  309. }
  310. $result = @pg_exec($this->connection, $query);
  311. if (!$result) {
  312. return $this->pgsqlRaiseError();
  313. }
  314. /*
  315. * Determine whether queries produce affected rows, result or nothing.
  316. *
  317. * This logic was introduced in version 1.1 of the file by ssb,
  318. * though the regex has been modified slightly since then.
  319. *
  320. * PostgreSQL commands:
  321. * ABORT, ALTER, BEGIN, CLOSE, CLUSTER, COMMIT, COPY,
  322. * CREATE, DECLARE, DELETE, DROP TABLE, EXPLAIN, FETCH,
  323. * GRANT, INSERT, LISTEN, LOAD, LOCK, MOVE, NOTIFY, RESET,
  324. * REVOKE, ROLLBACK, SELECT, SELECT INTO, SET, SHOW,
  325. * UNLISTEN, UPDATE, VACUUM, WITH
  326. */
  327. if ($ismanip) {
  328. $this->affected = @pg_affected_rows($result);
  329. return DB_OK;
  330. } elseif (preg_match(
  331. '/^\s*\(*\s*(SELECT|EXPLAIN|FETCH|SHOW|WITH)\s/si',
  332. $query
  333. )) {
  334. $this->row[(int)$result] = 0; // reset the row counter.
  335. $numrows = $this->numRows($result);
  336. if (is_object($numrows)) {
  337. return $numrows;
  338. }
  339. $this->_num_rows[(int)$result] = $numrows;
  340. $this->affected = 0;
  341. return $result;
  342. } else {
  343. $this->affected = 0;
  344. return DB_OK;
  345. }
  346. }
  347. // }}}
  348. // {{{ nextResult()
  349. /**
  350. * Checks if the given query is a manipulation query. This also takes into
  351. * account the _next_query_manip flag and sets the _last_query_manip flag
  352. * (and resets _next_query_manip) according to the result.
  353. *
  354. * @param string The query to check.
  355. *
  356. * @return boolean true if the query is a manipulation query, false
  357. * otherwise
  358. *
  359. * @access protected
  360. */
  361. public function _checkManip($query)
  362. {
  363. return (preg_match('/^\s*(SAVEPOINT|RELEASE)\s+/i', $query)
  364. || parent::_checkManip($query));
  365. }
  366. // }}}
  367. // {{{ fetchInto()
  368. /**
  369. * Produces a DB_Error object regarding the current problem
  370. *
  371. * @param int $errno if the error is being manually raised pass a
  372. * DB_ERROR* constant here. If this isn't passed
  373. * the error information gathered from the DBMS.
  374. *
  375. * @return object the DB_Error object
  376. *
  377. * @see DB_common::raiseError(),
  378. * DB_pgsql::errorNative(), DB_pgsql::errorCode()
  379. */
  380. public function pgsqlRaiseError($errno = null)
  381. {
  382. $native = $this->errorNative();
  383. if (!$native) {
  384. $native = 'Database connection has been lost.';
  385. $errno = DB_ERROR_CONNECT_FAILED;
  386. }
  387. if ($errno === null) {
  388. $errno = $this->errorCode($native);
  389. }
  390. return $this->raiseError($errno, null, null, null, $native);
  391. }
  392. // }}}
  393. // {{{ freeResult()
  394. /**
  395. * Gets the DBMS' native error message produced by the last query
  396. *
  397. * {@internal Error messages are used instead of error codes
  398. * in order to support older versions of PostgreSQL.}}
  399. *
  400. * @return string the DBMS' error message
  401. */
  402. public function errorNative()
  403. {
  404. return @pg_errormessage($this->connection);
  405. }
  406. // }}}
  407. // {{{ quoteBoolean()
  408. /**
  409. * Determines PEAR::DB error code from the database's text error message.
  410. *
  411. * @param string $errormsg error message returned from the database
  412. * @return integer an error number from a DB error constant
  413. */
  414. public function errorCode($errormsg)
  415. {
  416. static $error_regexps;
  417. if (!isset($error_regexps)) {
  418. $error_regexps = array(
  419. '/column .* (of relation .*)?does not exist/i'
  420. => DB_ERROR_NOSUCHFIELD,
  421. '/(relation|sequence|table).*does not exist|class .* not found/i'
  422. => DB_ERROR_NOSUCHTABLE,
  423. '/index .* does not exist/'
  424. => DB_ERROR_NOT_FOUND,
  425. '/relation .* already exists/i'
  426. => DB_ERROR_ALREADY_EXISTS,
  427. '/(divide|division) by zero$/i'
  428. => DB_ERROR_DIVZERO,
  429. '/pg_atoi: error in .*: can\'t parse /i'
  430. => DB_ERROR_INVALID_NUMBER,
  431. '/invalid input syntax for( type)? (integer|numeric)/i'
  432. => DB_ERROR_INVALID_NUMBER,
  433. '/value .* is out of range for type \w*int/i'
  434. => DB_ERROR_INVALID_NUMBER,
  435. '/integer out of range/i'
  436. => DB_ERROR_INVALID_NUMBER,
  437. '/value too long for type character/i'
  438. => DB_ERROR_INVALID,
  439. '/attribute .* not found|relation .* does not have attribute/i'
  440. => DB_ERROR_NOSUCHFIELD,
  441. '/column .* specified in USING clause does not exist in (left|right) table/i'
  442. => DB_ERROR_NOSUCHFIELD,
  443. '/parser: parse error at or near/i'
  444. => DB_ERROR_SYNTAX,
  445. '/syntax error at/'
  446. => DB_ERROR_SYNTAX,
  447. '/column reference .* is ambiguous/i'
  448. => DB_ERROR_SYNTAX,
  449. '/permission denied/'
  450. => DB_ERROR_ACCESS_VIOLATION,
  451. '/violates not-null constraint/'
  452. => DB_ERROR_CONSTRAINT_NOT_NULL,
  453. '/violates [\w ]+ constraint/'
  454. => DB_ERROR_CONSTRAINT,
  455. '/referential integrity violation/'
  456. => DB_ERROR_CONSTRAINT,
  457. '/more expressions than target columns/i'
  458. => DB_ERROR_VALUE_COUNT_ON_ROW,
  459. );
  460. }
  461. foreach ($error_regexps as $regexp => $code) {
  462. if (preg_match($regexp, $errormsg)) {
  463. return $code;
  464. }
  465. }
  466. // Fall back to DB_ERROR if there was no mapping.
  467. return DB_ERROR;
  468. }
  469. // }}}
  470. // {{{ escapeSimple()
  471. /**
  472. * Gets the number of rows in a result set
  473. *
  474. * This method is not meant to be called directly. Use
  475. * DB_result::numRows() instead. It can't be declared "protected"
  476. * because DB_result is a separate object.
  477. *
  478. * @param resource $result PHP's query result resource
  479. *
  480. * @return int|object
  481. *
  482. * @see DB_result::numRows()
  483. */
  484. public function numRows($result)
  485. {
  486. $rows = @pg_numrows($result);
  487. if ($rows === null) {
  488. return $this->pgsqlRaiseError();
  489. }
  490. return $rows;
  491. }
  492. // }}}
  493. // {{{ numCols()
  494. /**
  495. * Move the internal pgsql result pointer to the next available result
  496. *
  497. * @param a valid fbsql result resource
  498. *
  499. * @access public
  500. *
  501. * @return true if a result is available otherwise return false
  502. */
  503. public function nextResult($result)
  504. {
  505. return false;
  506. }
  507. // }}}
  508. // {{{ numRows()
  509. /**
  510. * Places a row from the result set into the given array
  511. *
  512. * Formating of the array and the data therein are configurable.
  513. * See DB_result::fetchInto() for more information.
  514. *
  515. * This method is not meant to be called directly. Use
  516. * DB_result::fetchInto() instead. It can't be declared "protected"
  517. * because DB_result is a separate object.
  518. *
  519. * @param resource $result the query result resource
  520. * @param array $arr the referenced array to put the data in
  521. * @param int $fetchmode how the resulting array should be indexed
  522. * @param int $rownum the row number to fetch (0 = first row)
  523. *
  524. * @return mixed DB_OK on success, NULL when the end of a result set is
  525. * reached or on failure
  526. *
  527. * @see DB_result::fetchInto()
  528. */
  529. public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  530. {
  531. $result_int = (int)$result;
  532. $rownum = ($rownum !== null) ? $rownum : $this->row[$result_int];
  533. if ($rownum >= $this->_num_rows[$result_int]) {
  534. return null;
  535. }
  536. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  537. $arr = @pg_fetch_array($result, $rownum, PGSQL_ASSOC);
  538. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
  539. $arr = array_change_key_case($arr, CASE_LOWER);
  540. }
  541. } else {
  542. $arr = @pg_fetch_row($result, $rownum);
  543. }
  544. if (!$arr) {
  545. return null;
  546. }
  547. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  548. $this->_rtrimArrayValues($arr);
  549. }
  550. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  551. $this->_convertNullArrayValuesToEmpty($arr);
  552. }
  553. $this->row[$result_int] = ++$rownum;
  554. return DB_OK;
  555. }
  556. // }}}
  557. // {{{ autoCommit()
  558. /**
  559. * Deletes the result set and frees the memory occupied by the result set
  560. *
  561. * This method is not meant to be called directly. Use
  562. * DB_result::free() instead. It can't be declared "protected"
  563. * because DB_result is a separate object.
  564. *
  565. * @param resource $result PHP's query result resource
  566. *
  567. * @return bool TRUE on success, FALSE if $result is invalid
  568. *
  569. * @see DB_result::free()
  570. */
  571. public function freeResult($result)
  572. {
  573. if (is_resource($result)) {
  574. unset($this->row[(int)$result]);
  575. unset($this->_num_rows[(int)$result]);
  576. $this->affected = 0;
  577. return @pg_freeresult($result);
  578. }
  579. return false;
  580. }
  581. // }}}
  582. // {{{ commit()
  583. /**
  584. * Formats a boolean value for use within a query in a locale-independent
  585. * manner.
  586. *
  587. * @param boolean the boolean value to be quoted.
  588. * @return string the quoted string.
  589. * @see DB_common::quoteSmart()
  590. * @since Method available since release 1.7.8.
  591. */
  592. public function quoteBoolean($boolean)
  593. {
  594. return $boolean ? 'TRUE' : 'FALSE';
  595. }
  596. // }}}
  597. // {{{ rollback()
  598. /**
  599. * Escapes a string according to the current DBMS's standards
  600. *
  601. * {@internal PostgreSQL treats a backslash as an escape character,
  602. * so they are escaped as well.
  603. *
  604. * @param string $str the string to be escaped
  605. *
  606. * @return string the escaped string
  607. *
  608. * @see DB_common::quoteSmart()
  609. * @since Method available since Release 1.6.0
  610. */
  611. public function escapeSimple($str)
  612. {
  613. if (function_exists('pg_escape_string')) {
  614. /* This fixes an undocumented BC break in PHP 5.2.0 which changed
  615. * the prototype of pg_escape_string. I'm not thrilled about having
  616. * to sniff the PHP version, quite frankly, but it's the only way
  617. * to deal with the problem. Revision 1.331.2.13.2.10 on
  618. * php-src/ext/pgsql/pgsql.c (PHP_5_2 branch) is to blame, for the
  619. * record. */
  620. if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
  621. return pg_escape_string($this->connection, $str);
  622. } else {
  623. return pg_escape_string($str);
  624. }
  625. } else {
  626. return str_replace("'", "''", str_replace('\\', '\\\\', $str));
  627. }
  628. }
  629. // }}}
  630. // {{{ affectedRows()
  631. /**
  632. * Gets the number of columns in a result set
  633. *
  634. * This method is not meant to be called directly. Use
  635. * DB_result::numCols() instead. It can't be declared "protected"
  636. * because DB_result is a separate object.
  637. *
  638. * @param resource $result PHP's query result resource
  639. *
  640. * @return int|object
  641. *
  642. * @see DB_result::numCols()
  643. */
  644. public function numCols($result)
  645. {
  646. $cols = @pg_numfields($result);
  647. if (!$cols) {
  648. return $this->pgsqlRaiseError();
  649. }
  650. return $cols;
  651. }
  652. // }}}
  653. // {{{ nextId()
  654. /**
  655. * Enables or disables automatic commits
  656. *
  657. * @param bool $onoff true turns it on, false turns it off
  658. *
  659. * @return int DB_OK on success. A DB_Error object if the driver
  660. * doesn't support auto-committing transactions.
  661. */
  662. public function autoCommit($onoff = false)
  663. {
  664. // XXX if $this->transaction_opcount > 0, we should probably
  665. // issue a warning here.
  666. $this->autocommit = $onoff ? true : false;
  667. return DB_OK;
  668. }
  669. // }}}
  670. // {{{ createSequence()
  671. /**
  672. * Commits the current transaction
  673. *
  674. * @return int|object
  675. */
  676. public function commit()
  677. {
  678. if ($this->transaction_opcount > 0) {
  679. // (disabled) hack to shut up error messages from libpq.a
  680. //@fclose(@fopen("php://stderr", "w"));
  681. $result = @pg_exec($this->connection, 'end;');
  682. $this->transaction_opcount = 0;
  683. if (!$result) {
  684. return $this->pgsqlRaiseError();
  685. }
  686. }
  687. return DB_OK;
  688. }
  689. // }}}
  690. // {{{ dropSequence()
  691. /**
  692. * Reverts the current transaction
  693. *
  694. * @return int|object
  695. */
  696. public function rollback()
  697. {
  698. if ($this->transaction_opcount > 0) {
  699. $result = @pg_exec($this->connection, 'abort;');
  700. $this->transaction_opcount = 0;
  701. if (!$result) {
  702. return $this->pgsqlRaiseError();
  703. }
  704. }
  705. return DB_OK;
  706. }
  707. // }}}
  708. // {{{ modifyLimitQuery()
  709. /**
  710. * Determines the number of rows affected by a data maniuplation query
  711. *
  712. * 0 is returned for queries that don't manipulate data.
  713. *
  714. * @return int the number of rows. A DB_Error object on failure.
  715. */
  716. public function affectedRows()
  717. {
  718. return $this->affected;
  719. }
  720. // }}}
  721. // {{{ pgsqlRaiseError()
  722. /**
  723. * Returns the next free id in a sequence
  724. *
  725. * @param string $seq_name name of the sequence
  726. * @param boolean $ondemand when true, the seqence is automatically
  727. * created if it does not exist
  728. *
  729. * @return int|object
  730. * A DB_Error object on failure.
  731. *
  732. * @see DB_common::nextID(), DB_common::getSequenceName(),
  733. * DB_pgsql::createSequence(), DB_pgsql::dropSequence()
  734. */
  735. public function nextId($seq_name, $ondemand = true)
  736. {
  737. $seqname = $this->getSequenceName($seq_name);
  738. $repeat = false;
  739. do {
  740. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  741. $result = $this->query("SELECT NEXTVAL('${seqname}')");
  742. $this->popErrorHandling();
  743. if ($ondemand && DB::isError($result) &&
  744. $result->getCode() == DB_ERROR_NOSUCHTABLE) {
  745. $repeat = true;
  746. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  747. $result = $this->createSequence($seq_name);
  748. $this->popErrorHandling();
  749. if (DB::isError($result)) {
  750. return $this->raiseError($result);
  751. }
  752. } else {
  753. $repeat = false;
  754. }
  755. } while ($repeat);
  756. if (DB::isError($result)) {
  757. return $this->raiseError($result);
  758. }
  759. $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
  760. $result->free();
  761. return $arr[0];
  762. }
  763. // }}}
  764. // {{{ errorNative()
  765. /**
  766. * Creates a new sequence
  767. *
  768. * @param string $seq_name name of the new sequence
  769. *
  770. * @return int DB_OK on success. A DB_Error object on failure.
  771. *
  772. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  773. * DB_pgsql::nextID(), DB_pgsql::dropSequence()
  774. */
  775. public function createSequence($seq_name)
  776. {
  777. $seqname = $this->getSequenceName($seq_name);
  778. $result = $this->query("CREATE SEQUENCE ${seqname}");
  779. return $result;
  780. }
  781. // }}}
  782. // {{{ errorCode()
  783. /**
  784. * Deletes a sequence
  785. *
  786. * @param string $seq_name name of the sequence to be deleted
  787. *
  788. * @return int DB_OK on success. A DB_Error object on failure.
  789. *
  790. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  791. * DB_pgsql::nextID(), DB_pgsql::createSequence()
  792. */
  793. public function dropSequence($seq_name)
  794. {
  795. return $this->query('DROP SEQUENCE '
  796. . $this->getSequenceName($seq_name));
  797. }
  798. // }}}
  799. // {{{ tableInfo()
  800. /**
  801. * Adds LIMIT clauses to a query string according to current DBMS standards
  802. *
  803. * @param string $query the query to modify
  804. * @param int $from the row to start to fetching (0 = the first row)
  805. * @param int $count the numbers of rows to fetch
  806. * @param mixed $params array, string or numeric data to be used in
  807. * execution of the statement. Quantity of items
  808. * passed must match quantity of placeholders in
  809. * query: meaning 1 placeholder for non-array
  810. * parameters or 1 placeholder per array element.
  811. *
  812. * @return string the query string with LIMIT clauses added
  813. *
  814. * @access protected
  815. */
  816. public function modifyLimitQuery($query, $from, $count, $params = array())
  817. {
  818. return "$query LIMIT $count OFFSET $from";
  819. }
  820. // }}}
  821. // {{{ _pgFieldFlags()
  822. /**
  823. * Returns information about a table or a result set
  824. *
  825. * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  826. * is a table name.
  827. *
  828. * @param object|string $result DB_result object from a query or a
  829. * string containing the name of a table.
  830. * While this also accepts a query result
  831. * resource identifier, this behavior is
  832. * deprecated.
  833. * @param int $mode a valid tableInfo mode
  834. *
  835. * @return array|object
  836. * A DB_Error object on failure.
  837. *
  838. * @see DB_common::tableInfo()
  839. */
  840. public function tableInfo($result, $mode = null)
  841. {
  842. if (is_string($result)) {
  843. /*
  844. * Probably received a table name.
  845. * Create a result resource identifier.
  846. */
  847. $id = @pg_exec($this->connection, "SELECT * FROM $result LIMIT 0");
  848. $got_string = true;
  849. } elseif (isset($result->result)) {
  850. /*
  851. * Probably received a result object.
  852. * Extract the result resource identifier.
  853. */
  854. $id = $result->result;
  855. $got_string = false;
  856. } else {
  857. /*
  858. * Probably received a result resource identifier.
  859. * Copy it.
  860. * Deprecated. Here for compatibility only.
  861. */
  862. $id = $result;
  863. $got_string = false;
  864. }
  865. if (!is_resource($id)) {
  866. return $this->pgsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
  867. }
  868. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  869. $case_func = 'strtolower';
  870. } else {
  871. $case_func = 'strval';
  872. }
  873. $count = @pg_numfields($id);
  874. $res = array();
  875. if ($mode) {
  876. $res['num_fields'] = $count;
  877. }
  878. for ($i = 0; $i < $count; $i++) {
  879. $res[$i] = array(
  880. 'table' => $got_string ? $case_func($result) : '',
  881. 'name' => $case_func(@pg_fieldname($id, $i)),
  882. 'type' => @pg_fieldtype($id, $i),
  883. 'len' => @pg_fieldsize($id, $i),
  884. 'flags' => $got_string
  885. ? $this->_pgFieldFlags($id, $i, $result)
  886. : '',
  887. );
  888. if ($mode & DB_TABLEINFO_ORDER) {
  889. $res['order'][$res[$i]['name']] = $i;
  890. }
  891. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  892. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  893. }
  894. }
  895. // free the result only if we were called on a table
  896. if ($got_string) {
  897. @pg_freeresult($id);
  898. }
  899. return $res;
  900. }
  901. // }}}
  902. // {{{ getSpecialQuery()
  903. /**
  904. * Get a column's flags
  905. *
  906. * Supports "not_null", "default_value", "primary_key", "unique_key"
  907. * and "multiple_key". The default value is passed through
  908. * rawurlencode() in case there are spaces in it.
  909. *
  910. * @param int $resource the PostgreSQL result identifier
  911. * @param int $num_field the field number
  912. *
  913. * @param $table_name
  914. * @return string the flags
  915. *
  916. * @access private
  917. */
  918. public function _pgFieldFlags($resource, $num_field, $table_name)
  919. {
  920. $field_name = @pg_fieldname($resource, $num_field);
  921. // Check if there's a schema in $table_name and update things
  922. // accordingly.
  923. $from = 'pg_attribute f, pg_class tab, pg_type typ';
  924. if (strpos($table_name, '.') !== false) {
  925. $from .= ', pg_namespace nsp';
  926. list($schema, $table) = explode('.', $table_name);
  927. $tableWhere = "tab.relname = '$table' AND tab.relnamespace = nsp.oid AND nsp.nspname = '$schema'";
  928. } else {
  929. $tableWhere = "tab.relname = '$table_name'";
  930. }
  931. $result = @pg_exec($this->connection, "SELECT f.attnotnull, f.atthasdef
  932. FROM $from
  933. WHERE tab.relname = typ.typname
  934. AND typ.typrelid = f.attrelid
  935. AND f.attname = '$field_name'
  936. AND $tableWhere");
  937. if (@pg_numrows($result) > 0) {
  938. $row = @pg_fetch_row($result, 0);
  939. $flags = ($row[0] == 't') ? 'not_null ' : '';
  940. if ($row[1] == 't') {
  941. $result = @pg_exec($this->connection, "SELECT a.adsrc
  942. FROM $from, pg_attrdef a
  943. WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
  944. AND f.attrelid = a.adrelid AND f.attname = '$field_name'
  945. AND $tableWhere AND f.attnum = a.adnum");
  946. $row = @pg_fetch_row($result, 0);
  947. $num = preg_replace("/'(.*)'::\w+/", "\\1", $row[0]);
  948. $flags .= 'default_' . rawurlencode($num) . ' ';
  949. }
  950. } else {
  951. $flags = '';
  952. }
  953. $result = @pg_exec($this->connection, "SELECT i.indisunique, i.indisprimary, i.indkey
  954. FROM $from, pg_index i
  955. WHERE tab.relname = typ.typname
  956. AND typ.typrelid = f.attrelid
  957. AND f.attrelid = i.indrelid
  958. AND f.attname = '$field_name'
  959. AND $tableWhere");
  960. $count = @pg_numrows($result);
  961. for ($i = 0; $i < $count; $i++) {
  962. $row = @pg_fetch_row($result, $i);
  963. $keys = explode(' ', $row[2]);
  964. if (in_array($num_field + 1, $keys)) {
  965. $flags .= ($row[0] == 't' && $row[1] == 'f') ? 'unique_key ' : '';
  966. $flags .= ($row[1] == 't') ? 'primary_key ' : '';
  967. if (count($keys) > 1) {
  968. $flags .= 'multiple_key ';
  969. }
  970. }
  971. }
  972. return trim($flags);
  973. }
  974. // }}}
  975. // {{{ _checkManip()
  976. /**
  977. * Obtains the query string needed for listing a given type of objects
  978. *
  979. * @param string $type the kind of objects you want to retrieve
  980. *
  981. * @return string the SQL query string or null if the driver doesn't
  982. * support the object type requested
  983. *
  984. * @access protected
  985. * @see DB_common::getListOf()
  986. */
  987. public function getSpecialQuery($type)
  988. {
  989. switch ($type) {
  990. case 'tables':
  991. return 'SELECT c.relname AS "Name"'
  992. . ' FROM pg_class c, pg_user u'
  993. . ' WHERE c.relowner = u.usesysid'
  994. . " AND c.relkind = 'r'"
  995. . ' AND NOT EXISTS'
  996. . ' (SELECT 1 FROM pg_views'
  997. . ' WHERE viewname = c.relname)'
  998. . " AND c.relname !~ '^(pg_|sql_)'"
  999. . ' UNION'
  1000. . ' SELECT c.relname AS "Name"'
  1001. . ' FROM pg_class c'
  1002. . " WHERE c.relkind = 'r'"
  1003. . ' AND NOT EXISTS'
  1004. . ' (SELECT 1 FROM pg_views'
  1005. . ' WHERE viewname = c.relname)'
  1006. . ' AND NOT EXISTS'
  1007. . ' (SELECT 1 FROM pg_user'
  1008. . ' WHERE usesysid = c.relowner)'
  1009. . " AND c.relname !~ '^pg_'";
  1010. case 'schema.tables':
  1011. return "SELECT schemaname || '.' || tablename"
  1012. . ' AS "Name"'
  1013. . ' FROM pg_catalog.pg_tables'
  1014. . ' WHERE schemaname NOT IN'
  1015. . " ('pg_catalog', 'information_schema', 'pg_toast')";
  1016. case 'schema.views':
  1017. return "SELECT schemaname || '.' || viewname from pg_views WHERE schemaname"
  1018. . " NOT IN ('information_schema', 'pg_catalog')";
  1019. case 'views':
  1020. // Table cols: viewname | viewowner | definition
  1021. return 'SELECT viewname from pg_views WHERE schemaname'
  1022. . " NOT IN ('information_schema', 'pg_catalog')";
  1023. case 'users':
  1024. // cols: usename |usesysid|usecreatedb|usetrace|usesuper|usecatupd|passwd |valuntil
  1025. return 'SELECT usename FROM pg_user';
  1026. case 'databases':
  1027. return 'SELECT datname FROM pg_database';
  1028. case 'functions':
  1029. case 'procedures':
  1030. return 'SELECT proname FROM pg_proc WHERE proowner <> 1';
  1031. default:
  1032. return null;
  1033. }
  1034. }
  1035. }
  1036. /*
  1037. * Local variables:
  1038. * tab-width: 4
  1039. * c-basic-offset: 4
  1040. * End:
  1041. */