pgsql.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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 (MDB2::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 (MDB2::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 (MDB2::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 (MDB2::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 (!extension_loaded($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 (MDB2::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 (MDB2::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 (MDB2::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 (!MDB2::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 (MDB2::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 (!MDB2::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 (MDB2::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 (MDB2::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 (MDB2::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 (MDB2::isError($server_info)) {
  750. return $server_info;
  751. }
  752. }
  753. // cache server_info
  754. $this->connected_server_info = $server_info;
  755. if (!$native && !MDB2::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 (MDB2::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 (MDB2::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 (MDB2::isError($connection)) {
  913. return $connection;
  914. }
  915. static $prep_statement_counter = 1;
  916. $randomStr = sprintf('%d', $prep_statement_counter++) . sha1(microtime() . sprintf('%d', mt_rand()));
  917. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $randomStr);
  918. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  919. if (false === $pgtypes) {
  920. $result = @pg_prepare($connection, $statement_name, $query);
  921. if (!$result) {
  922. $err = $this->raiseError(null, null, null,
  923. 'Unable to create prepared statement handle', __FUNCTION__);
  924. return $err;
  925. }
  926. } else {
  927. $types_string = '';
  928. if ($pgtypes) {
  929. $types_string = ' ('.implode(', ', $pgtypes).') ';
  930. }
  931. $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
  932. $statement = $this->_doQuery($query, true, $connection);
  933. if (MDB2::isError($statement)) {
  934. return $statement;
  935. }
  936. }
  937. $class_name = 'MDB2_Statement_'.$this->phptype;
  938. $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  939. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  940. return $obj;
  941. }
  942. // }}}
  943. // {{{ function getSequenceName($sqn)
  944. /**
  945. * adds sequence name formatting to a sequence name
  946. *
  947. * @param string name of the sequence
  948. *
  949. * @return string formatted sequence name
  950. *
  951. * @access public
  952. */
  953. function getSequenceName($sqn)
  954. {
  955. if (false === $this->options['disable_smart_seqname']) {
  956. if (strpos($sqn, '_') !== false) {
  957. list($table, $field) = explode('_', $sqn, 2);
  958. }
  959. $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
  960. if (MDB2::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
  961. $order_by = ' a.attnum';
  962. $schema_clause = ' AND n.nspname=current_schema()';
  963. } else {
  964. $schemas = explode(',', $schema_list);
  965. $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
  966. $counter = 1;
  967. $order_by = ' CASE ';
  968. foreach ($schemas as $schema) {
  969. $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
  970. }
  971. $order_by .= ' ELSE '.$counter.' END, a.attnum';
  972. }
  973. $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
  974. FROM pg_attrdef d
  975. WHERE d.adrelid = a.attrelid
  976. AND d.adnum = a.attnum
  977. AND a.atthasdef
  978. ) FROM 'nextval[^'']*''([^'']*)')
  979. FROM pg_attribute a
  980. LEFT JOIN pg_class c ON c.oid = a.attrelid
  981. LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
  982. LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
  983. WHERE (c.relname = ".$this->quote($sqn, 'text');
  984. if (!empty($field)) {
  985. $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
  986. }
  987. $query .= " )"
  988. .$schema_clause."
  989. AND NOT a.attisdropped
  990. AND a.attnum > 0
  991. AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
  992. ORDER BY ".$order_by;
  993. $seqname = $this->queryOne($query);
  994. if (!MDB2::isError($seqname) && !empty($seqname) && is_string($seqname)) {
  995. return $seqname;
  996. }
  997. }
  998. return parent::getSequenceName($sqn);
  999. }
  1000. // }}}
  1001. // {{{ nextID()
  1002. /**
  1003. * Returns the next free id of a sequence
  1004. *
  1005. * @param string $seq_name name of the sequence
  1006. * @param boolean $ondemand when true the sequence is
  1007. * automatic created, if it
  1008. * not exists
  1009. * @return mixed MDB2 Error Object or id
  1010. * @access public
  1011. */
  1012. function nextID($seq_name, $ondemand = true)
  1013. {
  1014. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1015. $query = "SELECT NEXTVAL('$sequence_name')";
  1016. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  1017. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1018. $result = $this->queryOne($query, 'integer');
  1019. $this->popExpect();
  1020. $this->popErrorHandling();
  1021. if (MDB2::isError($result)) {
  1022. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  1023. $this->loadModule('Manager', null, true);
  1024. $result = $this->manager->createSequence($seq_name);
  1025. if (MDB2::isError($result)) {
  1026. return $this->raiseError($result, null, null,
  1027. 'on demand sequence could not be created', __FUNCTION__);
  1028. }
  1029. return $this->nextId($seq_name, false);
  1030. }
  1031. }
  1032. return $result;
  1033. }
  1034. // }}}
  1035. // {{{ lastInsertID()
  1036. /**
  1037. * Returns the autoincrement ID if supported or $id or fetches the current
  1038. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1039. *
  1040. * @param string $table name of the table into which a new row was inserted
  1041. * @param string $field name of the field into which a new row was inserted
  1042. * @return mixed MDB2 Error Object or id
  1043. * @access public
  1044. */
  1045. function lastInsertID($table = null, $field = null)
  1046. {
  1047. if (empty($table) && empty($field)) {
  1048. return $this->queryOne('SELECT lastval()', 'integer');
  1049. }
  1050. $seq = $table.(empty($field) ? '' : '_'.$field);
  1051. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
  1052. return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
  1053. }
  1054. // }}}
  1055. // {{{ currID()
  1056. /**
  1057. * Returns the current id of a sequence
  1058. *
  1059. * @param string $seq_name name of the sequence
  1060. * @return mixed MDB2 Error Object or id
  1061. * @access public
  1062. */
  1063. function currID($seq_name)
  1064. {
  1065. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1066. return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
  1067. }
  1068. }
  1069. /**
  1070. * MDB2 PostGreSQL result driver
  1071. *
  1072. * @package MDB2
  1073. * @category Database
  1074. * @author Paul Cooper <pgc@ucecom.com>
  1075. */
  1076. class MDB2_Result_pgsql extends MDB2_Result_Common
  1077. {
  1078. // }}}
  1079. // {{{ fetchRow()
  1080. /**
  1081. * Fetch a row and insert the data into an existing array.
  1082. *
  1083. * @param int $fetchmode how the array data should be indexed
  1084. * @param int $rownum number of the row where the data can be found
  1085. * @return int data array on success, a MDB2 error on failure
  1086. * @access public
  1087. */
  1088. function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1089. {
  1090. if (null !== $rownum) {
  1091. $seek = $this->seek($rownum);
  1092. if (MDB2::isError($seek)) {
  1093. return $seek;
  1094. }
  1095. }
  1096. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1097. $fetchmode = $this->db->fetchmode;
  1098. }
  1099. if ( $fetchmode == MDB2_FETCHMODE_ASSOC
  1100. || $fetchmode == MDB2_FETCHMODE_OBJECT
  1101. ) {
  1102. $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
  1103. if (is_array($row)
  1104. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1105. ) {
  1106. $row = array_change_key_case($row, $this->db->options['field_case']);
  1107. }
  1108. } else {
  1109. $row = @pg_fetch_row($this->result);
  1110. }
  1111. if (!$row) {
  1112. if (false === $this->result) {
  1113. $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1114. 'resultset has already been freed', __FUNCTION__);
  1115. return $err;
  1116. }
  1117. return null;
  1118. }
  1119. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1120. $rtrim = false;
  1121. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1122. if (empty($this->types)) {
  1123. $mode += MDB2_PORTABILITY_RTRIM;
  1124. } else {
  1125. $rtrim = true;
  1126. }
  1127. }
  1128. if ($mode) {
  1129. $this->db->_fixResultArrayValues($row, $mode);
  1130. }
  1131. if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
  1132. && $fetchmode != MDB2_FETCHMODE_OBJECT)
  1133. && !empty($this->types)
  1134. ) {
  1135. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1136. } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
  1137. || $fetchmode == MDB2_FETCHMODE_OBJECT)
  1138. && !empty($this->types_assoc)
  1139. ) {
  1140. $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1141. }
  1142. if (!empty($this->values)) {
  1143. $this->_assignBindColumns($row);
  1144. }
  1145. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1146. $object_class = $this->db->options['fetch_class'];
  1147. if ($object_class == 'stdClass') {
  1148. $row = (object) $row;
  1149. } else {
  1150. $rowObj = new $object_class($row);
  1151. $row = $rowObj;
  1152. }
  1153. }
  1154. ++$this->rownum;
  1155. return $row;
  1156. }
  1157. // }}}
  1158. // {{{ _getColumnNames()
  1159. /**
  1160. * Retrieve the names of columns returned by the DBMS in a query result.
  1161. *
  1162. * @return mixed Array variable that holds the names of columns as keys
  1163. * or an MDB2 error on failure.
  1164. * Some DBMS may not return any columns when the result set
  1165. * does not contain any rows.
  1166. * @access private
  1167. */
  1168. function _getColumnNames()
  1169. {
  1170. $columns = array();
  1171. $numcols = $this->numCols();
  1172. if (MDB2::isError($numcols)) {
  1173. return $numcols;
  1174. }
  1175. for ($column = 0; $column < $numcols; $column++) {
  1176. $column_name = @pg_field_name($this->result, $column);
  1177. $columns[$column_name] = $column;
  1178. }
  1179. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1180. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1181. }
  1182. return $columns;
  1183. }
  1184. // }}}
  1185. // {{{ numCols()
  1186. /**
  1187. * Count the number of columns returned by the DBMS in a query result.
  1188. *
  1189. * @access public
  1190. * @return mixed integer value with the number of columns, a MDB2 error
  1191. * on failure
  1192. */
  1193. function numCols()
  1194. {
  1195. $cols = @pg_num_fields($this->result);
  1196. if (null === $cols) {
  1197. if (false === $this->result) {
  1198. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1199. 'resultset has already been freed', __FUNCTION__);
  1200. }
  1201. if (null === $this->result) {
  1202. return count($this->types);
  1203. }
  1204. return $this->db->raiseError(null, null, null,
  1205. 'Could not get column count', __FUNCTION__);
  1206. }
  1207. return $cols;
  1208. }
  1209. // }}}
  1210. // {{{ nextResult()
  1211. /**
  1212. * Move the internal result pointer to the next available result
  1213. *
  1214. * @return true on success, false if there is no more result set or an error object on failure
  1215. * @access public
  1216. */
  1217. function nextResult()
  1218. {
  1219. $connection = $this->db->getConnection();
  1220. if (MDB2::isError($connection)) {
  1221. return $connection;
  1222. }
  1223. if (!($this->result = @pg_get_result($connection))) {
  1224. return false;
  1225. }
  1226. return MDB2_OK;
  1227. }
  1228. // }}}
  1229. // {{{ free()
  1230. /**
  1231. * Free the internal resources associated with result.
  1232. *
  1233. * @return boolean true on success, false if result is invalid
  1234. * @access public
  1235. */
  1236. function free()
  1237. {
  1238. if (is_resource($this->result) && $this->db->connection) {
  1239. $free = @pg_free_result($this->result);
  1240. if (false === $free) {
  1241. return $this->db->raiseError(null, null, null,
  1242. 'Could not free result', __FUNCTION__);
  1243. }
  1244. }
  1245. $this->result = false;
  1246. return MDB2_OK;
  1247. }
  1248. }
  1249. /**
  1250. * MDB2 PostGreSQL buffered result driver
  1251. *
  1252. * @package MDB2
  1253. * @category Database
  1254. * @author Paul Cooper <pgc@ucecom.com>
  1255. */
  1256. class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
  1257. {
  1258. // {{{ seek()
  1259. /**
  1260. * Seek to a specific row in a result set
  1261. *
  1262. * @param int $rownum number of the row where the data can be found
  1263. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1264. * @access public
  1265. */
  1266. function seek($rownum = 0)
  1267. {
  1268. if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
  1269. if (false === $this->result) {
  1270. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1271. 'resultset has already been freed', __FUNCTION__);
  1272. }
  1273. if (null === $this->result) {
  1274. return MDB2_OK;
  1275. }
  1276. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1277. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1278. }
  1279. $this->rownum = $rownum - 1;
  1280. return MDB2_OK;
  1281. }
  1282. // }}}
  1283. // {{{ valid()
  1284. /**
  1285. * Check if the end of the result set has been reached
  1286. *
  1287. * @return mixed true or false on sucess, a MDB2 error on failure
  1288. * @access public
  1289. */
  1290. function valid()
  1291. {
  1292. $numrows = $this->numRows();
  1293. if (MDB2::isError($numrows)) {
  1294. return $numrows;
  1295. }
  1296. return $this->rownum < ($numrows - 1);
  1297. }
  1298. // }}}
  1299. // {{{ numRows()
  1300. /**
  1301. * Returns the number of rows in a result object
  1302. *
  1303. * @return mixed MDB2 Error Object or the number of rows
  1304. * @access public
  1305. */
  1306. function numRows()
  1307. {
  1308. $rows = @pg_num_rows($this->result);
  1309. if (null === $rows) {
  1310. if (false === $this->result) {
  1311. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1312. 'resultset has already been freed', __FUNCTION__);
  1313. }
  1314. if (null === $this->result) {
  1315. return 0;
  1316. }
  1317. return $this->db->raiseError(null, null, null,
  1318. 'Could not get row count', __FUNCTION__);
  1319. }
  1320. return $rows;
  1321. }
  1322. }
  1323. /**
  1324. * MDB2 PostGreSQL statement driver
  1325. *
  1326. * @package MDB2
  1327. * @category Database
  1328. * @author Paul Cooper <pgc@ucecom.com>
  1329. */
  1330. class MDB2_Statement_pgsql extends MDB2_Statement_Common
  1331. {
  1332. // {{{ _execute()
  1333. /**
  1334. * Execute a prepared query statement helper method.
  1335. *
  1336. * @param mixed $result_class string which specifies which result class to use
  1337. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1338. *
  1339. * @return mixed MDB2_Result or integer (affected rows) on success,
  1340. * a MDB2 error on failure
  1341. * @access private
  1342. */
  1343. function _execute($result_class = true, $result_wrap_class = true)
  1344. {
  1345. if (null === $this->statement) {
  1346. return parent::_execute($result_class, $result_wrap_class);
  1347. }
  1348. $this->db->last_query = $this->query;
  1349. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1350. if ($this->db->getOption('disable_query')) {
  1351. $result = $this->is_manip ? 0 : null;
  1352. return $result;
  1353. }
  1354. $connection = $this->db->getConnection();
  1355. if (MDB2::isError($connection)) {
  1356. return $connection;
  1357. }
  1358. $query = false;
  1359. $parameters = array();
  1360. // todo: disabled until pg_execute() bytea issues are cleared up
  1361. if (true || !function_exists('pg_execute')) {
  1362. $query = 'EXECUTE '.$this->statement;
  1363. }
  1364. if (!empty($this->positions)) {
  1365. foreach ($this->positions as $parameter) {
  1366. if (!array_key_exists($parameter, $this->values)) {
  1367. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1368. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1369. }
  1370. $value = $this->values[$parameter];
  1371. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1372. if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
  1373. if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1374. if ($match[1] == 'file://') {
  1375. $value = $match[2];
  1376. }
  1377. $value = @fopen($value, 'r');
  1378. $close = true;
  1379. }
  1380. if (is_resource($value)) {
  1381. $data = '';
  1382. while (!@feof($value)) {
  1383. $data.= @fread($value, $this->db->options['lob_buffer_length']);
  1384. }
  1385. if ($close) {
  1386. @fclose($value);
  1387. }
  1388. $value = $data;
  1389. }
  1390. }
  1391. $quoted = $this->db->quote($value, $type, $query);
  1392. if (MDB2::isError($quoted)) {
  1393. return $quoted;
  1394. }
  1395. $parameters[] = $quoted;
  1396. }
  1397. if ($query) {
  1398. $query.= ' ('.implode(', ', $parameters).')';
  1399. }
  1400. }
  1401. if (!$query) {
  1402. $result = @pg_execute($connection, $this->statement, $parameters);
  1403. if (!$result) {
  1404. $err = $this->db->raiseError(null, null, null,
  1405. 'Unable to execute statement', __FUNCTION__);
  1406. return $err;
  1407. }
  1408. } else {
  1409. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1410. if (MDB2::isError($result)) {
  1411. return $result;
  1412. }
  1413. }
  1414. if ($this->is_manip) {
  1415. $affected_rows = $this->db->_affectedRows($connection, $result);
  1416. return $affected_rows;
  1417. }
  1418. $result = $this->db->_wrapResult($result, $this->result_types,
  1419. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1420. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1421. return $result;
  1422. }
  1423. // }}}
  1424. // {{{ free()
  1425. /**
  1426. * Release resources allocated for the specified prepared query.
  1427. *
  1428. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1429. * @access public
  1430. */
  1431. function free()
  1432. {
  1433. if (null === $this->positions) {
  1434. return $this->db->raiseError(MDB2_ERROR, null, null,
  1435. 'Prepared statement has already been freed', __FUNCTION__);
  1436. }
  1437. $result = MDB2_OK;
  1438. if (null !== $this->statement) {
  1439. $connection = $this->db->getConnection();
  1440. if (MDB2::isError($connection)) {
  1441. return $connection;
  1442. }
  1443. $query = 'DEALLOCATE PREPARE '.$this->statement;
  1444. $result = $this->db->_doQuery($query, true, $connection);
  1445. }
  1446. parent::free();
  1447. return $result;
  1448. }
  1449. /**
  1450. * drop an existing table
  1451. *
  1452. * @param string $name name of the table that should be dropped
  1453. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1454. * @access public
  1455. */
  1456. function dropTable($name)
  1457. {
  1458. $db = $this->getDBInstance();
  1459. if (MDB2::isError($db)) {
  1460. return $db;
  1461. }
  1462. $name = $db->quoteIdentifier($name, true);
  1463. $result = $db->exec("DROP TABLE $name");
  1464. if (MDB2::isError($result)) {
  1465. $result = $db->exec("DROP TABLE $name CASCADE");
  1466. }
  1467. return $result;
  1468. }
  1469. }
  1470. ?>