source: branches/comu-ver2/data/module/MDB2/Driver/pgsql.php @ 18754

Revision 18754, 54.8 KB checked in by nanasess, 14 years ago (diff)

PEAR::MDB2 のライブラリ追加(#564)

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