source: subversion/trunk/roundcubemail/program/lib/MDB2/Driver/pgsql.php @ 3227

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