pgsql.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Paul Cooper <pgc@ucecom.com> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id$
  47. /**
  48. * MDB2 PostGreSQL driver
  49. *
  50. * @package MDB2
  51. * @category Database
  52. * @author Paul Cooper <pgc@ucecom.com>
  53. */
  54. class MDB2_Driver_pgsql extends MDB2_Driver_Common
  55. {
  56. // {{{ properties
  57. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
  58. var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
  59. // }}}
  60. // {{{ constructor
  61. /**
  62. * Constructor
  63. */
  64. function __construct()
  65. {
  66. parent::__construct();
  67. $this->phptype = 'pgsql';
  68. $this->dbsyntax = 'pgsql';
  69. $this->supported['sequences'] = true;
  70. $this->supported['indexes'] = true;
  71. $this->supported['affected_rows'] = true;
  72. $this->supported['summary_functions'] = true;
  73. $this->supported['order_by_text'] = true;
  74. $this->supported['transactions'] = true;
  75. $this->supported['savepoints'] = true;
  76. $this->supported['current_id'] = true;
  77. $this->supported['limit_queries'] = true;
  78. $this->supported['LOBs'] = true;
  79. $this->supported['replace'] = 'emulated';
  80. $this->supported['sub_selects'] = true;
  81. $this->supported['triggers'] = true;
  82. $this->supported['auto_increment'] = 'emulated';
  83. $this->supported['primary_key'] = true;
  84. $this->supported['result_introspection'] = true;
  85. $this->supported['prepared_statements'] = true;
  86. $this->supported['identifier_quoting'] = true;
  87. $this->supported['pattern_escaping'] = true;
  88. $this->supported['new_link'] = true;
  89. $this->options['DBA_username'] = false;
  90. $this->options['DBA_password'] = false;
  91. $this->options['multi_query'] = false;
  92. $this->options['disable_smart_seqname'] = true;
  93. $this->options['max_identifiers_length'] = 63;
  94. }
  95. // }}}
  96. // {{{ errorInfo()
  97. /**
  98. * This method is used to collect information about an error
  99. *
  100. * @param integer $error
  101. * @return array
  102. * @access public
  103. */
  104. function errorInfo($error = null)
  105. {
  106. // Fall back to MDB2_ERROR if there was no mapping.
  107. $error_code = MDB2_ERROR;
  108. $native_msg = '';
  109. if (is_resource($error)) {
  110. $native_msg = @pg_result_error($error);
  111. } elseif ($this->connection) {
  112. $native_msg = @pg_last_error($this->connection);
  113. if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
  114. $native_msg = 'Database connection has been lost.';
  115. $error_code = MDB2_ERROR_CONNECT_FAILED;
  116. }
  117. } else {
  118. $native_msg = @pg_last_error();
  119. }
  120. static $error_regexps;
  121. if (empty($error_regexps)) {
  122. $error_regexps = array(
  123. '/column .* (of relation .*)?does not exist/i'
  124. => MDB2_ERROR_NOSUCHFIELD,
  125. '/(relation|sequence|table).*does not exist|class .* not found/i'
  126. => MDB2_ERROR_NOSUCHTABLE,
  127. '/database .* does not exist/'
  128. => MDB2_ERROR_NOT_FOUND,
  129. '/constraint .* does not exist/'
  130. => MDB2_ERROR_NOT_FOUND,
  131. '/index .* does not exist/'
  132. => MDB2_ERROR_NOT_FOUND,
  133. '/database .* already exists/i'
  134. => MDB2_ERROR_ALREADY_EXISTS,
  135. '/relation .* already exists/i'
  136. => MDB2_ERROR_ALREADY_EXISTS,
  137. '/(divide|division) by zero$/i'
  138. => MDB2_ERROR_DIVZERO,
  139. '/pg_atoi: error in .*: can\'t parse /i'
  140. => MDB2_ERROR_INVALID_NUMBER,
  141. '/invalid input syntax for( type)? (integer|numeric)/i'
  142. => MDB2_ERROR_INVALID_NUMBER,
  143. '/value .* is out of range for type \w*int/i'
  144. => MDB2_ERROR_INVALID_NUMBER,
  145. '/integer out of range/i'
  146. => MDB2_ERROR_INVALID_NUMBER,
  147. '/value too long for type character/i'
  148. => MDB2_ERROR_INVALID,
  149. '/attribute .* not found|relation .* does not have attribute/i'
  150. => MDB2_ERROR_NOSUCHFIELD,
  151. '/column .* specified in USING clause does not exist in (left|right) table/i'
  152. => MDB2_ERROR_NOSUCHFIELD,
  153. '/parser: parse error at or near/i'
  154. => MDB2_ERROR_SYNTAX,
  155. '/syntax error at/'
  156. => MDB2_ERROR_SYNTAX,
  157. '/column reference .* is ambiguous/i'
  158. => MDB2_ERROR_SYNTAX,
  159. '/permission denied/'
  160. => MDB2_ERROR_ACCESS_VIOLATION,
  161. '/violates not-null constraint/'
  162. => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  163. '/violates [\w ]+ constraint/'
  164. => MDB2_ERROR_CONSTRAINT,
  165. '/referential integrity violation/'
  166. => MDB2_ERROR_CONSTRAINT,
  167. '/more expressions than target columns/i'
  168. => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  169. );
  170. }
  171. if (is_numeric($error) && $error < 0) {
  172. $error_code = $error;
  173. } else {
  174. foreach ($error_regexps as $regexp => $code) {
  175. if (preg_match($regexp, $native_msg)) {
  176. $error_code = $code;
  177. break;
  178. }
  179. }
  180. }
  181. return array($error_code, null, $native_msg);
  182. }
  183. // }}}
  184. // {{{ escape()
  185. /**
  186. * Quotes a string so it can be safely used in a query. It will quote
  187. * the text so it can safely be used within a query.
  188. *
  189. * @param string the input string to quote
  190. * @param bool escape wildcards
  191. *
  192. * @return string quoted string
  193. *
  194. * @access public
  195. */
  196. function escape($text, $escape_wildcards = false)
  197. {
  198. if ($escape_wildcards) {
  199. $text = $this->escapePattern($text);
  200. }
  201. $connection = $this->getConnection();
  202. if (PEAR::isError($connection)) {
  203. return $connection;
  204. }
  205. if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
  206. $text = @pg_escape_string($connection, $text);
  207. } else {
  208. $text = @pg_escape_string($text);
  209. }
  210. return $text;
  211. }
  212. // }}}
  213. // {{{ beginTransaction()
  214. /**
  215. * Start a transaction or set a savepoint.
  216. *
  217. * @param string name of a savepoint to set
  218. * @return mixed MDB2_OK on success, a MDB2 error on failure
  219. *
  220. * @access public
  221. */
  222. function beginTransaction($savepoint = null)
  223. {
  224. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  225. if (null !== $savepoint) {
  226. if (!$this->in_transaction) {
  227. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  228. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  229. }
  230. $query = 'SAVEPOINT '.$savepoint;
  231. return $this->_doQuery($query, true);
  232. }
  233. if ($this->in_transaction) {
  234. return MDB2_OK; //nothing to do
  235. }
  236. if (!$this->destructor_registered && $this->opened_persistent) {
  237. $this->destructor_registered = true;
  238. register_shutdown_function('MDB2_closeOpenTransactions');
  239. }
  240. $result = $this->_doQuery('BEGIN', true);
  241. if (PEAR::isError($result)) {
  242. return $result;
  243. }
  244. $this->in_transaction = true;
  245. return MDB2_OK;
  246. }
  247. // }}}
  248. // {{{ commit()
  249. /**
  250. * Commit the database changes done during a transaction that is in
  251. * progress or release a savepoint. This function may only be called when
  252. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  253. * transaction is implicitly started after committing the pending changes.
  254. *
  255. * @param string name of a savepoint to release
  256. * @return mixed MDB2_OK on success, a MDB2 error on failure
  257. *
  258. * @access public
  259. */
  260. function commit($savepoint = null)
  261. {
  262. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  263. if (!$this->in_transaction) {
  264. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  265. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  266. }
  267. if (null !== $savepoint) {
  268. $query = 'RELEASE SAVEPOINT '.$savepoint;
  269. return $this->_doQuery($query, true);
  270. }
  271. $result = $this->_doQuery('COMMIT', true);
  272. if (PEAR::isError($result)) {
  273. return $result;
  274. }
  275. $this->in_transaction = false;
  276. return MDB2_OK;
  277. }
  278. // }}}
  279. // {{{ rollback()
  280. /**
  281. * Cancel any database changes done during a transaction or since a specific
  282. * savepoint that is in progress. This function may only be called when
  283. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  284. * transaction is implicitly started after canceling the pending changes.
  285. *
  286. * @param string name of a savepoint to rollback to
  287. * @return mixed MDB2_OK on success, a MDB2 error on failure
  288. *
  289. * @access public
  290. */
  291. function rollback($savepoint = null)
  292. {
  293. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  294. if (!$this->in_transaction) {
  295. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  296. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  297. }
  298. if (null !== $savepoint) {
  299. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  300. return $this->_doQuery($query, true);
  301. }
  302. $query = 'ROLLBACK';
  303. $result = $this->_doQuery($query, true);
  304. if (PEAR::isError($result)) {
  305. return $result;
  306. }
  307. $this->in_transaction = false;
  308. return MDB2_OK;
  309. }
  310. // }}}
  311. // {{{ function setTransactionIsolation()
  312. /**
  313. * Set the transacton isolation level.
  314. *
  315. * @param string standard isolation level
  316. * READ UNCOMMITTED (allows dirty reads)
  317. * READ COMMITTED (prevents dirty reads)
  318. * REPEATABLE READ (prevents nonrepeatable reads)
  319. * SERIALIZABLE (prevents phantom reads)
  320. * @param array some transaction options:
  321. * 'wait' => 'WAIT' | 'NO WAIT'
  322. * 'rw' => 'READ WRITE' | 'READ ONLY'
  323. *
  324. * @return mixed MDB2_OK on success, a MDB2 error on failure
  325. *
  326. * @access public
  327. * @since 2.1.1
  328. */
  329. function setTransactionIsolation($isolation, $options = array())
  330. {
  331. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  332. switch ($isolation) {
  333. case 'READ UNCOMMITTED':
  334. case 'READ COMMITTED':
  335. case 'REPEATABLE READ':
  336. case 'SERIALIZABLE':
  337. break;
  338. default:
  339. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  340. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  341. }
  342. $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
  343. return $this->_doQuery($query, true);
  344. }
  345. // }}}
  346. // {{{ _doConnect()
  347. /**
  348. * Do the grunt work of connecting to the database
  349. *
  350. * @return mixed connection resource on success, MDB2 Error Object on failure
  351. * @access protected
  352. */
  353. function _doConnect($username, $password, $database_name, $persistent = false)
  354. {
  355. if (!PEAR::loadExtension($this->phptype)) {
  356. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  357. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  358. }
  359. if ($database_name == '') {
  360. $database_name = 'template1';
  361. }
  362. $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
  363. $params = array('');
  364. if ($protocol == 'tcp') {
  365. if ($this->dsn['hostspec']) {
  366. $params[0].= 'host=' . $this->dsn['hostspec'];
  367. }
  368. if ($this->dsn['port']) {
  369. $params[0].= ' port=' . $this->dsn['port'];
  370. }
  371. } elseif ($protocol == 'unix') {
  372. // Allow for pg socket in non-standard locations.
  373. if ($this->dsn['socket']) {
  374. $params[0].= 'host=' . $this->dsn['socket'];
  375. }
  376. if ($this->dsn['port']) {
  377. $params[0].= ' port=' . $this->dsn['port'];
  378. }
  379. }
  380. if ($database_name) {
  381. $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
  382. }
  383. if ($username) {
  384. $params[0].= ' user=\'' . addslashes($username) . '\'';
  385. }
  386. if ($password) {
  387. $params[0].= ' password=\'' . addslashes($password) . '\'';
  388. }
  389. if (!empty($this->dsn['options'])) {
  390. $params[0].= ' options=' . $this->dsn['options'];
  391. }
  392. if (!empty($this->dsn['tty'])) {
  393. $params[0].= ' tty=' . $this->dsn['tty'];
  394. }
  395. if (!empty($this->dsn['connect_timeout'])) {
  396. $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
  397. }
  398. if (!empty($this->dsn['sslmode'])) {
  399. $params[0].= ' sslmode=' . $this->dsn['sslmode'];
  400. }
  401. if (!empty($this->dsn['service'])) {
  402. $params[0].= ' service=' . $this->dsn['service'];
  403. }
  404. if ($this->_isNewLinkSet()) {
  405. if (version_compare(phpversion(), '4.3.0', '>=')) {
  406. $params[] = PGSQL_CONNECT_FORCE_NEW;
  407. }
  408. }
  409. $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
  410. $connection = @call_user_func_array($connect_function, $params);
  411. if (!$connection) {
  412. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  413. 'unable to establish a connection', __FUNCTION__);
  414. }
  415. if (empty($this->dsn['disable_iso_date'])) {
  416. if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
  417. return $this->raiseError(null, null, null,
  418. 'Unable to set date style to iso', __FUNCTION__);
  419. }
  420. }
  421. if (!empty($this->dsn['charset'])) {
  422. $result = $this->setCharset($this->dsn['charset'], $connection);
  423. if (PEAR::isError($result)) {
  424. return $result;
  425. }
  426. }
  427. // Enable extra compatibility settings on 8.2 and later
  428. if (function_exists('pg_parameter_status')) {
  429. $version = pg_parameter_status($connection, 'server_version');
  430. if ($version == false) {
  431. return $this->raiseError(null, null, null,
  432. 'Unable to retrieve server version', __FUNCTION__);
  433. }
  434. $version = explode ('.', $version);
  435. if ( $version['0'] > 8
  436. || ($version['0'] == 8 && $version['1'] >= 2)
  437. ) {
  438. if (!@pg_query($connection, "SET SESSION STANDARD_CONFORMING_STRINGS = OFF")) {
  439. return $this->raiseError(null, null, null,
  440. 'Unable to set standard_conforming_strings to off', __FUNCTION__);
  441. }
  442. if (!@pg_query($connection, "SET SESSION ESCAPE_STRING_WARNING = OFF")) {
  443. return $this->raiseError(null, null, null,
  444. 'Unable to set escape_string_warning to off', __FUNCTION__);
  445. }
  446. }
  447. }
  448. return $connection;
  449. }
  450. // }}}
  451. // {{{ connect()
  452. /**
  453. * Connect to the database
  454. *
  455. * @return true on success, MDB2 Error Object on failure
  456. * @access public
  457. */
  458. function connect()
  459. {
  460. if (is_resource($this->connection)) {
  461. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  462. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  463. && $this->connected_database_name == $this->database_name
  464. && ($this->opened_persistent == $this->options['persistent'])
  465. ) {
  466. return MDB2_OK;
  467. }
  468. $this->disconnect(false);
  469. }
  470. if ($this->database_name) {
  471. $connection = $this->_doConnect($this->dsn['username'],
  472. $this->dsn['password'],
  473. $this->database_name,
  474. $this->options['persistent']);
  475. if (PEAR::isError($connection)) {
  476. return $connection;
  477. }
  478. $this->connection = $connection;
  479. $this->connected_dsn = $this->dsn;
  480. $this->connected_database_name = $this->database_name;
  481. $this->opened_persistent = $this->options['persistent'];
  482. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  483. }
  484. return MDB2_OK;
  485. }
  486. // }}}
  487. // {{{ setCharset()
  488. /**
  489. * Set the charset on the current connection
  490. *
  491. * @param string charset
  492. * @param resource connection handle
  493. *
  494. * @return true on success, MDB2 Error Object on failure
  495. */
  496. function setCharset($charset, $connection = null)
  497. {
  498. if (null === $connection) {
  499. $connection = $this->getConnection();
  500. if (PEAR::isError($connection)) {
  501. return $connection;
  502. }
  503. }
  504. if (is_array($charset)) {
  505. $charset = array_shift($charset);
  506. $this->warnings[] = 'postgresql does not support setting client collation';
  507. }
  508. $result = @pg_set_client_encoding($connection, $charset);
  509. if ($result == -1) {
  510. return $this->raiseError(null, null, null,
  511. 'Unable to set client charset: '.$charset, __FUNCTION__);
  512. }
  513. return MDB2_OK;
  514. }
  515. // }}}
  516. // {{{ databaseExists()
  517. /**
  518. * check if given database name is exists?
  519. *
  520. * @param string $name name of the database that should be checked
  521. *
  522. * @return mixed true/false on success, a MDB2 error on failure
  523. * @access public
  524. */
  525. function databaseExists($name)
  526. {
  527. $res = $this->_doConnect($this->dsn['username'],
  528. $this->dsn['password'],
  529. $this->escape($name),
  530. $this->options['persistent']);
  531. if (!PEAR::isError($res)) {
  532. return true;
  533. }
  534. return false;
  535. }
  536. // }}}
  537. // {{{ disconnect()
  538. /**
  539. * Log out and disconnect from the database.
  540. *
  541. * @param boolean $force if the disconnect should be forced even if the
  542. * connection is opened persistently
  543. * @return mixed true on success, false if not connected and error
  544. * object on error
  545. * @access public
  546. */
  547. function disconnect($force = true)
  548. {
  549. if (is_resource($this->connection)) {
  550. if ($this->in_transaction) {
  551. $dsn = $this->dsn;
  552. $database_name = $this->database_name;
  553. $persistent = $this->options['persistent'];
  554. $this->dsn = $this->connected_dsn;
  555. $this->database_name = $this->connected_database_name;
  556. $this->options['persistent'] = $this->opened_persistent;
  557. $this->rollback();
  558. $this->dsn = $dsn;
  559. $this->database_name = $database_name;
  560. $this->options['persistent'] = $persistent;
  561. }
  562. if (!$this->opened_persistent || $force) {
  563. $ok = @pg_close($this->connection);
  564. if (!$ok) {
  565. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  566. null, null, null, __FUNCTION__);
  567. }
  568. }
  569. } else {
  570. return false;
  571. }
  572. return parent::disconnect($force);
  573. }
  574. // }}}
  575. // {{{ standaloneQuery()
  576. /**
  577. * execute a query as DBA
  578. *
  579. * @param string $query the SQL query
  580. * @param mixed $types array that contains the types of the columns in
  581. * the result set
  582. * @param boolean $is_manip if the query is a manipulation query
  583. * @return mixed MDB2_OK on success, a MDB2 error on failure
  584. * @access public
  585. */
  586. function standaloneQuery($query, $types = null, $is_manip = false)
  587. {
  588. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  589. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  590. $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
  591. if (PEAR::isError($connection)) {
  592. return $connection;
  593. }
  594. $offset = $this->offset;
  595. $limit = $this->limit;
  596. $this->offset = $this->limit = 0;
  597. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  598. $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  599. if (!PEAR::isError($result)) {
  600. if ($is_manip) {
  601. $result = $this->_affectedRows($connection, $result);
  602. } else {
  603. $result = $this->_wrapResult($result, $types, true, true, $limit, $offset);
  604. }
  605. }
  606. @pg_close($connection);
  607. return $result;
  608. }
  609. // }}}
  610. // {{{ _doQuery()
  611. /**
  612. * Execute a query
  613. * @param string $query query
  614. * @param boolean $is_manip if the query is a manipulation query
  615. * @param resource $connection
  616. * @param string $database_name
  617. * @return result or error object
  618. * @access protected
  619. */
  620. function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  621. {
  622. $this->last_query = $query;
  623. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  624. if ($result) {
  625. if (PEAR::isError($result)) {
  626. return $result;
  627. }
  628. $query = $result;
  629. }
  630. if ($this->options['disable_query']) {
  631. $result = $is_manip ? 0 : null;
  632. return $result;
  633. }
  634. if (null === $connection) {
  635. $connection = $this->getConnection();
  636. if (PEAR::isError($connection)) {
  637. return $connection;
  638. }
  639. }
  640. $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
  641. $result = @$function($connection, $query);
  642. if (!$result) {
  643. $err = $this->raiseError(null, null, null,
  644. 'Could not execute statement', __FUNCTION__);
  645. return $err;
  646. } elseif ($this->options['multi_query']) {
  647. if (!($result = @pg_get_result($connection))) {
  648. $err = $this->raiseError(null, null, null,
  649. 'Could not get the first result from a multi query', __FUNCTION__);
  650. return $err;
  651. }
  652. }
  653. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  654. return $result;
  655. }
  656. // }}}
  657. // {{{ _affectedRows()
  658. /**
  659. * Returns the number of rows affected
  660. *
  661. * @param resource $result
  662. * @param resource $connection
  663. * @return mixed MDB2 Error Object or the number of rows affected
  664. * @access private
  665. */
  666. function _affectedRows($connection, $result = null)
  667. {
  668. if (null === $connection) {
  669. $connection = $this->getConnection();
  670. if (PEAR::isError($connection)) {
  671. return $connection;
  672. }
  673. }
  674. return @pg_affected_rows($result);
  675. }
  676. // }}}
  677. // {{{ _modifyQuery()
  678. /**
  679. * Changes a query string for various DBMS specific reasons
  680. *
  681. * @param string $query query to modify
  682. * @param boolean $is_manip if it is a DML query
  683. * @param integer $limit limit the number of rows
  684. * @param integer $offset start reading from given offset
  685. * @return string modified query
  686. * @access protected
  687. */
  688. function _modifyQuery($query, $is_manip, $limit, $offset)
  689. {
  690. if ($limit > 0
  691. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  692. ) {
  693. $query = rtrim($query);
  694. if (substr($query, -1) == ';') {
  695. $query = substr($query, 0, -1);
  696. }
  697. if ($is_manip) {
  698. $query = $this->_modifyManipQuery($query, $limit);
  699. } else {
  700. $query.= " LIMIT $limit OFFSET $offset";
  701. }
  702. }
  703. return $query;
  704. }
  705. // }}}
  706. // {{{ _modifyManipQuery()
  707. /**
  708. * Changes a manip query string for various DBMS specific reasons
  709. *
  710. * @param string $query query to modify
  711. * @param integer $limit limit the number of rows
  712. * @return string modified query
  713. * @access protected
  714. */
  715. function _modifyManipQuery($query, $limit)
  716. {
  717. $pos = strpos(strtolower($query), 'where');
  718. $where = $pos ? substr($query, $pos) : '';
  719. $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
  720. $from_clause = '([\w\.]+)';
  721. $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
  722. $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
  723. $matches = preg_match($pattern, $query, $match);
  724. if ($matches) {
  725. $manip = $match[1];
  726. $from = $match[2];
  727. $what = (count($matches) == 6) ? $match[5] : $match[3];
  728. return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
  729. }
  730. //return error?
  731. return $query;
  732. }
  733. // }}}
  734. // {{{ getServerVersion()
  735. /**
  736. * return version information about the server
  737. *
  738. * @param bool $native determines if the raw version string should be returned
  739. * @return mixed array/string with version information or MDB2 error object
  740. * @access public
  741. */
  742. function getServerVersion($native = false)
  743. {
  744. $query = 'SHOW SERVER_VERSION';
  745. if ($this->connected_server_info) {
  746. $server_info = $this->connected_server_info;
  747. } else {
  748. $server_info = $this->queryOne($query, 'text');
  749. if (PEAR::isError($server_info)) {
  750. return $server_info;
  751. }
  752. }
  753. // cache server_info
  754. $this->connected_server_info = $server_info;
  755. if (!$native && !PEAR::isError($server_info)) {
  756. $tmp = explode('.', $server_info, 3);
  757. if (empty($tmp[2])
  758. && isset($tmp[1])
  759. && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
  760. ) {
  761. $server_info = array(
  762. 'major' => $tmp[0],
  763. 'minor' => $tmp2[1],
  764. 'patch' => null,
  765. 'extra' => $tmp2[2],
  766. 'native' => $server_info,
  767. );
  768. } else {
  769. $server_info = array(
  770. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  771. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  772. 'patch' => isset($tmp[2]) ? $tmp[2] : null,
  773. 'extra' => null,
  774. 'native' => $server_info,
  775. );
  776. }
  777. }
  778. return $server_info;
  779. }
  780. // }}}
  781. // {{{ prepare()
  782. /**
  783. * Prepares a query for multiple execution with execute().
  784. * With some database backends, this is emulated.
  785. * prepare() requires a generic query as string like
  786. * 'INSERT INTO numbers VALUES(?,?)' or
  787. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  788. * The ? and :name and are placeholders which can be set using
  789. * bindParam() and the query can be sent off using the execute() method.
  790. * The allowed format for :name can be set with the 'bindname_format' option.
  791. *
  792. * @param string $query the query to prepare
  793. * @param mixed $types array that contains the types of the placeholders
  794. * @param mixed $result_types array that contains the types of the columns in
  795. * the result set or MDB2_PREPARE_RESULT, if set to
  796. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  797. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  798. * @return mixed resource handle for the prepared query on success, a MDB2
  799. * error on failure
  800. * @access public
  801. * @see bindParam, execute
  802. */
  803. function prepare($query, $types = null, $result_types = null, $lobs = array())
  804. {
  805. if ($this->options['emulate_prepared']) {
  806. return parent::prepare($query, $types, $result_types, $lobs);
  807. }
  808. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  809. $offset = $this->offset;
  810. $limit = $this->limit;
  811. $this->offset = $this->limit = 0;
  812. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  813. if ($result) {
  814. if (PEAR::isError($result)) {
  815. return $result;
  816. }
  817. $query = $result;
  818. }
  819. $pgtypes = function_exists('pg_prepare') ? false : array();
  820. if ($pgtypes !== false && !empty($types)) {
  821. $this->loadModule('Datatype', null, true);
  822. }
  823. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  824. $placeholder_type_guess = $placeholder_type = null;
  825. $question = '?';
  826. $colon = ':';
  827. $positions = array();
  828. $position = $parameter = 0;
  829. while ($position < strlen($query)) {
  830. $q_position = strpos($query, $question, $position);
  831. $c_position = strpos($query, $colon, $position);
  832. //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
  833. $doublecolon_position = strpos($query, '::', $position);
  834. if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
  835. $c_position = strpos($query, $colon, $position+2);
  836. }
  837. if ($q_position && $c_position) {
  838. $p_position = min($q_position, $c_position);
  839. } elseif ($q_position) {
  840. $p_position = $q_position;
  841. } elseif ($c_position) {
  842. $p_position = $c_position;
  843. } else {
  844. break;
  845. }
  846. if (null === $placeholder_type) {
  847. $placeholder_type_guess = $query[$p_position];
  848. }
  849. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  850. if (PEAR::isError($new_pos)) {
  851. return $new_pos;
  852. }
  853. if ($new_pos != $position) {
  854. $position = $new_pos;
  855. continue; //evaluate again starting from the new position
  856. }
  857. if ($query[$position] == $placeholder_type_guess) {
  858. if (null === $placeholder_type) {
  859. $placeholder_type = $query[$p_position];
  860. $question = $colon = $placeholder_type;
  861. if (!empty($types) && is_array($types)) {
  862. if ($placeholder_type == ':') {
  863. } else {
  864. $types = array_values($types);
  865. }
  866. }
  867. }
  868. if ($placeholder_type_guess == '?') {
  869. $length = 1;
  870. $name = $parameter;
  871. } else {
  872. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  873. $param = preg_replace($regexp, '\\1', $query);
  874. if ($param === '') {
  875. $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  876. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  877. return $err;
  878. }
  879. $length = strlen($param) + 1;
  880. $name = $param;
  881. }
  882. if ($pgtypes !== false) {
  883. if (is_array($types) && array_key_exists($name, $types)) {
  884. $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
  885. } elseif (is_array($types) && array_key_exists($parameter, $types)) {
  886. $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
  887. } else {
  888. $pgtypes[] = 'text';
  889. }
  890. }
  891. if (($key_parameter = array_search($name, $positions)) !== false) {
  892. //$next_parameter = 1;
  893. $parameter = $key_parameter + 1;
  894. //foreach ($positions as $key => $value) {
  895. // if ($key_parameter == $key) {
  896. // break;
  897. // }
  898. // ++$next_parameter;
  899. //}
  900. } else {
  901. ++$parameter;
  902. //$next_parameter = $parameter;
  903. $positions[] = $name;
  904. }
  905. $query = substr_replace($query, '$'.$parameter, $position, $length);
  906. $position = $p_position + strlen($parameter);
  907. } else {
  908. $position = $p_position;
  909. }
  910. }
  911. $connection = $this->getConnection();
  912. if (PEAR::isError($connection)) {
  913. return $connection;
  914. }
  915. static $prep_statement_counter = 1;
  916. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
  917. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  918. if (false === $pgtypes) {
  919. $result = @pg_prepare($connection, $statement_name, $query);
  920. if (!$result) {
  921. $err = $this->raiseError(null, null, null,
  922. 'Unable to create prepared statement handle', __FUNCTION__);
  923. return $err;
  924. }
  925. } else {
  926. $types_string = '';
  927. if ($pgtypes) {
  928. $types_string = ' ('.implode(', ', $pgtypes).') ';
  929. }
  930. $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  931. $statement = $this->_doQuery($query, true, $connection);
  932. if (PEAR::isError($statement)) {
  933. return $statement;
  934. }
  935. }
  936. $class_name = 'MDB2_Statement_'.$this->phptype;
  937. $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  938. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  939. return $obj;
  940. }
  941. // }}}
  942. // {{{ function getSequenceName($sqn)
  943. /**
  944. * adds sequence name formatting to a sequence name
  945. *
  946. * @param string name of the sequence
  947. *
  948. * @return string formatted sequence name
  949. *
  950. * @access public
  951. */
  952. function getSequenceName($sqn)
  953. {
  954. if (false === $this->options['disable_smart_seqname']) {
  955. if (strpos($sqn, '_') !== false) {
  956. list($table, $field) = explode('_', $sqn, 2);
  957. }
  958. $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
  959. if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
  960. $order_by = ' a.attnum';
  961. $schema_clause = ' AND n.nspname=current_schema()';
  962. } else {
  963. $schemas = explode(',', $schema_list);
  964. $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
  965. $counter = 1;
  966. $order_by = ' CASE ';
  967. foreach ($schemas as $schema) {
  968. $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
  969. }
  970. $order_by .= ' ELSE '.$counter.' END, a.attnum';
  971. }
  972. $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
  973. FROM pg_attrdef d
  974. WHERE d.adrelid = a.attrelid
  975. AND d.adnum = a.attnum
  976. AND a.atthasdef
  977. ) FROM 'nextval[^'']*''([^'']*)')
  978. FROM pg_attribute a
  979. LEFT JOIN pg_class c ON c.oid = a.attrelid
  980. LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
  981. LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
  982. WHERE (c.relname = ".$this->quote($sqn, 'text');
  983. if (!empty($field)) {
  984. $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
  985. }
  986. $query .= " )"
  987. .$schema_clause."
  988. AND NOT a.attisdropped
  989. AND a.attnum > 0
  990. AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
  991. ORDER BY ".$order_by;
  992. $seqname = $this->queryOne($query);
  993. if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
  994. return $seqname;
  995. }
  996. }
  997. return parent::getSequenceName($sqn);
  998. }
  999. // }}}
  1000. // {{{ nextID()
  1001. /**
  1002. * Returns the next free id of a sequence
  1003. *
  1004. * @param string $seq_name name of the sequence
  1005. * @param boolean $ondemand when true the sequence is
  1006. * automatic created, if it
  1007. * not exists
  1008. * @return mixed MDB2 Error Object or id
  1009. * @access public
  1010. */
  1011. function nextID($seq_name, $ondemand = true)
  1012. {
  1013. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1014. $query = "SELECT NEXTVAL('$sequence_name')";
  1015. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  1016. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1017. $result = $this->queryOne($query, 'integer');
  1018. $this->popExpect();
  1019. $this->popErrorHandling();
  1020. if (PEAR::isError($result)) {
  1021. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  1022. $this->loadModule('Manager', null, true);
  1023. $result = $this->manager->createSequence($seq_name);
  1024. if (PEAR::isError($result)) {
  1025. return $this->raiseError($result, null, null,
  1026. 'on demand sequence could not be created', __FUNCTION__);
  1027. }
  1028. return $this->nextId($seq_name, false);
  1029. }
  1030. }
  1031. return $result;
  1032. }
  1033. // }}}
  1034. // {{{ lastInsertID()
  1035. /**
  1036. * Returns the autoincrement ID if supported or $id or fetches the current
  1037. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1038. *
  1039. * @param string $table name of the table into which a new row was inserted
  1040. * @param string $field name of the field into which a new row was inserted
  1041. * @return mixed MDB2 Error Object or id
  1042. * @access public
  1043. */
  1044. function lastInsertID($table = null, $field = null)
  1045. {
  1046. if (empty($table) && empty($field)) {
  1047. return $this->queryOne('SELECT lastval()', 'integer');
  1048. }
  1049. $seq = $table.(empty($field) ? '' : '_'.$field);
  1050. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
  1051. return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
  1052. }
  1053. // }}}
  1054. // {{{ currID()
  1055. /**
  1056. * Returns the current id of a sequence
  1057. *
  1058. * @param string $seq_name name of the sequence
  1059. * @return mixed MDB2 Error Object or id
  1060. * @access public
  1061. */
  1062. function currID($seq_name)
  1063. {
  1064. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1065. return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
  1066. }
  1067. }
  1068. /**
  1069. * MDB2 PostGreSQL result driver
  1070. *
  1071. * @package MDB2
  1072. * @category Database
  1073. * @author Paul Cooper <pgc@ucecom.com>
  1074. */
  1075. class MDB2_Result_pgsql extends MDB2_Result_Common
  1076. {
  1077. // }}}
  1078. // {{{ fetchRow()
  1079. /**
  1080. * Fetch a row and insert the data into an existing array.
  1081. *
  1082. * @param int $fetchmode how the array data should be indexed
  1083. * @param int $rownum number of the row where the data can be found
  1084. * @return int data array on success, a MDB2 error on failure
  1085. * @access public
  1086. */
  1087. function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1088. {
  1089. if (null !== $rownum) {
  1090. $seek = $this->seek($rownum);
  1091. if (PEAR::isError($seek)) {
  1092. return $seek;
  1093. }
  1094. }
  1095. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1096. $fetchmode = $this->db->fetchmode;
  1097. }
  1098. if ( $fetchmode == MDB2_FETCHMODE_ASSOC
  1099. || $fetchmode == MDB2_FETCHMODE_OBJECT
  1100. ) {
  1101. $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
  1102. if (is_array($row)
  1103. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1104. ) {
  1105. $row = array_change_key_case($row, $this->db->options['field_case']);
  1106. }
  1107. } else {
  1108. $row = @pg_fetch_row($this->result);
  1109. }
  1110. if (!$row) {
  1111. if (false === $this->result) {
  1112. $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1113. 'resultset has already been freed', __FUNCTION__);
  1114. return $err;
  1115. }
  1116. return null;
  1117. }
  1118. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1119. $rtrim = false;
  1120. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1121. if (empty($this->types)) {
  1122. $mode += MDB2_PORTABILITY_RTRIM;
  1123. } else {
  1124. $rtrim = true;
  1125. }
  1126. }
  1127. if ($mode) {
  1128. $this->db->_fixResultArrayValues($row, $mode);
  1129. }
  1130. if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
  1131. && $fetchmode != MDB2_FETCHMODE_OBJECT)
  1132. && !empty($this->types)
  1133. ) {
  1134. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1135. } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
  1136. || $fetchmode == MDB2_FETCHMODE_OBJECT)
  1137. && !empty($this->types_assoc)
  1138. ) {
  1139. $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1140. }
  1141. if (!empty($this->values)) {
  1142. $this->_assignBindColumns($row);
  1143. }
  1144. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1145. $object_class = $this->db->options['fetch_class'];
  1146. if ($object_class == 'stdClass') {
  1147. $row = (object) $row;
  1148. } else {
  1149. $rowObj = new $object_class($row);
  1150. $row = $rowObj;
  1151. }
  1152. }
  1153. ++$this->rownum;
  1154. return $row;
  1155. }
  1156. // }}}
  1157. // {{{ _getColumnNames()
  1158. /**
  1159. * Retrieve the names of columns returned by the DBMS in a query result.
  1160. *
  1161. * @return mixed Array variable that holds the names of columns as keys
  1162. * or an MDB2 error on failure.
  1163. * Some DBMS may not return any columns when the result set
  1164. * does not contain any rows.
  1165. * @access private
  1166. */
  1167. function _getColumnNames()
  1168. {
  1169. $columns = array();
  1170. $numcols = $this->numCols();
  1171. if (PEAR::isError($numcols)) {
  1172. return $numcols;
  1173. }
  1174. for ($column = 0; $column < $numcols; $column++) {
  1175. $column_name = @pg_field_name($this->result, $column);
  1176. $columns[$column_name] = $column;
  1177. }
  1178. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1179. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1180. }
  1181. return $columns;
  1182. }
  1183. // }}}
  1184. // {{{ numCols()
  1185. /**
  1186. * Count the number of columns returned by the DBMS in a query result.
  1187. *
  1188. * @access public
  1189. * @return mixed integer value with the number of columns, a MDB2 error
  1190. * on failure
  1191. */
  1192. function numCols()
  1193. {
  1194. $cols = @pg_num_fields($this->result);
  1195. if (null === $cols) {
  1196. if (false === $this->result) {
  1197. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1198. 'resultset has already been freed', __FUNCTION__);
  1199. }
  1200. if (null === $this->result) {
  1201. return count($this->types);
  1202. }
  1203. return $this->db->raiseError(null, null, null,
  1204. 'Could not get column count', __FUNCTION__);
  1205. }
  1206. return $cols;
  1207. }
  1208. // }}}
  1209. // {{{ nextResult()
  1210. /**
  1211. * Move the internal result pointer to the next available result
  1212. *
  1213. * @return true on success, false if there is no more result set or an error object on failure
  1214. * @access public
  1215. */
  1216. function nextResult()
  1217. {
  1218. $connection = $this->db->getConnection();
  1219. if (PEAR::isError($connection)) {
  1220. return $connection;
  1221. }
  1222. if (!($this->result = @pg_get_result($connection))) {
  1223. return false;
  1224. }
  1225. return MDB2_OK;
  1226. }
  1227. // }}}
  1228. // {{{ free()
  1229. /**
  1230. * Free the internal resources associated with result.
  1231. *
  1232. * @return boolean true on success, false if result is invalid
  1233. * @access public
  1234. */
  1235. function free()
  1236. {
  1237. if (is_resource($this->result) && $this->db->connection) {
  1238. $free = @pg_free_result($this->result);
  1239. if (false === $free) {
  1240. return $this->db->raiseError(null, null, null,
  1241. 'Could not free result', __FUNCTION__);
  1242. }
  1243. }
  1244. $this->result = false;
  1245. return MDB2_OK;
  1246. }
  1247. }
  1248. /**
  1249. * MDB2 PostGreSQL buffered result driver
  1250. *
  1251. * @package MDB2
  1252. * @category Database
  1253. * @author Paul Cooper <pgc@ucecom.com>
  1254. */
  1255. class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
  1256. {
  1257. // {{{ seek()
  1258. /**
  1259. * Seek to a specific row in a result set
  1260. *
  1261. * @param int $rownum number of the row where the data can be found
  1262. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1263. * @access public
  1264. */
  1265. function seek($rownum = 0)
  1266. {
  1267. if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
  1268. if (false === $this->result) {
  1269. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1270. 'resultset has already been freed', __FUNCTION__);
  1271. }
  1272. if (null === $this->result) {
  1273. return MDB2_OK;
  1274. }
  1275. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1276. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1277. }
  1278. $this->rownum = $rownum - 1;
  1279. return MDB2_OK;
  1280. }
  1281. // }}}
  1282. // {{{ valid()
  1283. /**
  1284. * Check if the end of the result set has been reached
  1285. *
  1286. * @return mixed true or false on sucess, a MDB2 error on failure
  1287. * @access public
  1288. */
  1289. function valid()
  1290. {
  1291. $numrows = $this->numRows();
  1292. if (PEAR::isError($numrows)) {
  1293. return $numrows;
  1294. }
  1295. return $this->rownum < ($numrows - 1);
  1296. }
  1297. // }}}
  1298. // {{{ numRows()
  1299. /**
  1300. * Returns the number of rows in a result object
  1301. *
  1302. * @return mixed MDB2 Error Object or the number of rows
  1303. * @access public
  1304. */
  1305. function numRows()
  1306. {
  1307. $rows = @pg_num_rows($this->result);
  1308. if (null === $rows) {
  1309. if (false === $this->result) {
  1310. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1311. 'resultset has already been freed', __FUNCTION__);
  1312. }
  1313. if (null === $this->result) {
  1314. return 0;
  1315. }
  1316. return $this->db->raiseError(null, null, null,
  1317. 'Could not get row count', __FUNCTION__);
  1318. }
  1319. return $rows;
  1320. }
  1321. }
  1322. /**
  1323. * MDB2 PostGreSQL statement driver
  1324. *
  1325. * @package MDB2
  1326. * @category Database
  1327. * @author Paul Cooper <pgc@ucecom.com>
  1328. */
  1329. class MDB2_Statement_pgsql extends MDB2_Statement_Common
  1330. {
  1331. // {{{ _execute()
  1332. /**
  1333. * Execute a prepared query statement helper method.
  1334. *
  1335. * @param mixed $result_class string which specifies which result class to use
  1336. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1337. *
  1338. * @return mixed MDB2_Result or integer (affected rows) on success,
  1339. * a MDB2 error on failure
  1340. * @access private
  1341. */
  1342. function _execute($result_class = true, $result_wrap_class = true)
  1343. {
  1344. if (null === $this->statement) {
  1345. return parent::_execute($result_class, $result_wrap_class);
  1346. }
  1347. $this->db->last_query = $this->query;
  1348. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1349. if ($this->db->getOption('disable_query')) {
  1350. $result = $this->is_manip ? 0 : null;
  1351. return $result;
  1352. }
  1353. $connection = $this->db->getConnection();
  1354. if (PEAR::isError($connection)) {
  1355. return $connection;
  1356. }
  1357. $query = false;
  1358. $parameters = array();
  1359. // todo: disabled until pg_execute() bytea issues are cleared up
  1360. if (true || !function_exists('pg_execute')) {
  1361. $query = 'EXECUTE '.$this->statement;
  1362. }
  1363. if (!empty($this->positions)) {
  1364. foreach ($this->positions as $parameter) {
  1365. if (!array_key_exists($parameter, $this->values)) {
  1366. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1367. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1368. }
  1369. $value = $this->values[$parameter];
  1370. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1371. if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
  1372. if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1373. if ($match[1] == 'file://') {
  1374. $value = $match[2];
  1375. }
  1376. $value = @fopen($value, 'r');
  1377. $close = true;
  1378. }
  1379. if (is_resource($value)) {
  1380. $data = '';
  1381. while (!@feof($value)) {
  1382. $data.= @fread($value, $this->db->options['lob_buffer_length']);
  1383. }
  1384. if ($close) {
  1385. @fclose($value);
  1386. }
  1387. $value = $data;
  1388. }
  1389. }
  1390. $quoted = $this->db->quote($value, $type, $query);
  1391. if (PEAR::isError($quoted)) {
  1392. return $quoted;
  1393. }
  1394. $parameters[] = $quoted;
  1395. }
  1396. if ($query) {
  1397. $query.= ' ('.implode(', ', $parameters).')';
  1398. }
  1399. }
  1400. if (!$query) {
  1401. $result = @pg_execute($connection, $this->statement, $parameters);
  1402. if (!$result) {
  1403. $err = $this->db->raiseError(null, null, null,
  1404. 'Unable to execute statement', __FUNCTION__);
  1405. return $err;
  1406. }
  1407. } else {
  1408. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1409. if (PEAR::isError($result)) {
  1410. return $result;
  1411. }
  1412. }
  1413. if ($this->is_manip) {
  1414. $affected_rows = $this->db->_affectedRows($connection, $result);
  1415. return $affected_rows;
  1416. }
  1417. $result = $this->db->_wrapResult($result, $this->result_types,
  1418. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1419. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1420. return $result;
  1421. }
  1422. // }}}
  1423. // {{{ free()
  1424. /**
  1425. * Release resources allocated for the specified prepared query.
  1426. *
  1427. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1428. * @access public
  1429. */
  1430. function free()
  1431. {
  1432. if (null === $this->positions) {
  1433. return $this->db->raiseError(MDB2_ERROR, null, null,
  1434. 'Prepared statement has already been freed', __FUNCTION__);
  1435. }
  1436. $result = MDB2_OK;
  1437. if (null !== $this->statement) {
  1438. $connection = $this->db->getConnection();
  1439. if (PEAR::isError($connection)) {
  1440. return $connection;
  1441. }
  1442. $query = 'DEALLOCATE PREPARE '.$this->statement;
  1443. $result = $this->db->_doQuery($query, true, $connection);
  1444. }
  1445. parent::free();
  1446. return $result;
  1447. }
  1448. /**
  1449. * drop an existing table
  1450. *
  1451. * @param string $name name of the table that should be dropped
  1452. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1453. * @access public
  1454. */
  1455. function dropTable($name)
  1456. {
  1457. $db = $this->getDBInstance();
  1458. if (PEAR::isError($db)) {
  1459. return $db;
  1460. }
  1461. $name = $db->quoteIdentifier($name, true);
  1462. $result = $db->exec("DROP TABLE $name");
  1463. if (PEAR::isError($result)) {
  1464. $result = $db->exec("DROP TABLE $name CASCADE");
  1465. }
  1466. return $result;
  1467. }
  1468. }
  1469. ?>