source: branches/version-2_13-dev/data/module/MDB2/Driver/pgsql.php @ 23022

Revision 23022, 57.0 KB checked in by Seasoft, 11 years ago (diff)

#2322 (セッションのGC処理がエラーとなる)

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