code:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * The PEAR DB driver for PHP's pgsql extension
 * for interacting with PostgreSQL databases
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Database
 * @package    DB
 * @author     Rui Hirokawa <hirokawa@php.net>
 * @author     Stig Bakken <ssb@php.net>
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  1997-2007 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    CVS: $Id$
 * @link       http://pear.php.net/package/DB
 */

/**
 * Obtain the DB_common class so it can be extended from
 */
//require_once 'DB/common.php';
require_once 'common.php';

/**
 * The methods PEAR DB uses to interact with PHP's pgsql extension
 * for interacting with PostgreSQL databases
 *
 * These methods overload the ones declared in DB_common.
 *
 * @category   Database
 * @package    DB
 * @author     Rui Hirokawa <hirokawa@php.net>
 * @author     Stig Bakken <ssb@php.net>
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  1997-2007 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: 1.9.2
 * @link       http://pear.php.net/package/DB
 */
class DB_pgsql extends DB_common
{
    // {{{ properties

    /**
     * The DB driver type (mysql, oci8, odbc, etc.)
     * @var string
     */
    public $phptype = 'pgsql';

    /**
     * The database syntax variant to be used (db2, access, etc.), if any
     * @var string
     */
    public $dbsyntax = 'pgsql';

    /**
     * The capabilities of this DB implementation
     *
     * The 'new_link' element contains the PHP version that first provided
     * new_link support for this DBMS.  Contains false if it's unsupported.
     *
     * Meaning of the 'limit' element:
     *   + 'emulate' = emulate with fetch row by number
     *   + 'alter'   = alter the query
     *   + false     = skip rows
     *
     * @var array
     */
    public $features = array(
        'limit' => 'alter',
        'new_link' => '4.3.0',
        'numrows' => true,
        'pconnect' => true,
        'prepare' => false,
        'ssl' => true,
        'transactions' => true,
    );

    /**
     * A mapping of native error codes to DB error codes
     * @var array
     */
    public $errorcode_map = array();

    /**
     * The raw database connection created by PHP
     * @var resource
     */
    public $connection;

    /**
     * The DSN information for connecting to a database
     * @var array
     */
    public $dsn = array();

    /**
     * Should data manipulation queries be committed automatically?
     * @var bool
     * @access private
     */
    public $autocommit = true;

    /**
     * The quantity of transactions begun
     *
     * {@internal  While this is private, it can't actually be designated
     * private in PHP 5 because it is directly accessed in the test suite.}}
     *
     * @var integer
     * @access private
     */
    public $transaction_opcount = 0;

    /**
     * The number of rows affected by a data manipulation query
     * @var integer
     */
    public $affected = 0;

    /**
     * The current row being looked at in fetchInto()
     * @var array
     * @access private
     */
    public $row = array();

    /**
     * The number of rows in a given result set
     * @var array
     * @access private
     */
    public $_num_rows = array();

    // }}}
    // {{{ constructor

    /**
     * This constructor calls parent::__construct()
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    // }}}
    // {{{ connect()

    /**
     * Connect to the database server, log in and open the database
     *
     * Don't call this method directly.  Use DB::connect() instead.
     *
     * PEAR DB's pgsql driver supports the following extra DSN options:
     *   + connect_timeout  How many seconds to wait for a connection to
     *                       be established.  Available since PEAR DB 1.7.0.
     *   + new_link         If set to true, causes subsequent calls to
     *                       connect() to return a new connection link
     *                       instead of the existing one.  WARNING: this is
     *                       not portable to other DBMS's.  Available only
     *                       if PHP is >= 4.3.0 and PEAR DB is >= 1.7.0.
     *   + options          Command line options to be sent to the server.
     *                       Available since PEAR DB 1.6.4.
     *   + service          Specifies a service name in pg_service.conf that
     *                       holds additional connection parameters.
     *                       Available since PEAR DB 1.7.0.
     *   + sslmode          How should SSL be used when connecting?  Values:
     *                       disable, allow, prefer or require.
     *                       Available since PEAR DB 1.7.0.
     *   + tty              This was used to specify where to send server
     *                       debug output.  Available since PEAR DB 1.6.4.
     *
     * Example of connecting to a new link via a socket:
     *
     * require_once 'DB.php';
     *
     * $dsn = 'pgsql://user:pass@unix(/tmp)/dbname?new_link=true';
     * $options = array(
     *     'portability' => DB_PORTABILITY_ALL,
     * );
     *
     * $db = DB::connect($dsn, $options);
     * if ((new PEAR)->isError($db)) {
     *     die($db->getMessage());
     * }
     *
     *
     * @param array $dsn the data source name
     * @param bool $persistent should the connection be persistent?
     *
     * @return int|object
     *
     * @link http://www.postgresql.org/docs/current/static/libpq.html#LIBPQ-CONNECT
     */
    public function connect($dsn, $persistent = false)
    {
        if (!PEAR::loadExtension('pgsql')) {
            return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
        }

        $this->dsn = $dsn;
        if ($dsn['dbsyntax']) {
            $this->dbsyntax = $dsn['dbsyntax'];
        }

        $protocol = $dsn['protocol'] ? $dsn['protocol'] : 'tcp';

        $params = array('');
        if ($protocol == 'tcp') {
            if ($dsn['hostspec']) {
                $params[0] .= 'host=' . $dsn['hostspec'];
            }
            if ($dsn['port']) {
                $params[0] .= ' port=' . $dsn['port'];
            }
        } elseif ($protocol == 'unix') {
            // Allow for pg socket in non-standard locations.
            if ($dsn['socket']) {
                $params[0] .= 'host=' . $dsn['socket'];
            }
            if ($dsn['port']) {
                $params[0] .= ' port=' . $dsn['port'];
            }
        }
        if ($dsn['database']) {
            $params[0] .= ' dbname=\'' . addslashes($dsn['database']) . '\'';
        }
        if ($dsn['username']) {
            $params[0] .= ' user=\'' . addslashes($dsn['username']) . '\'';
        }
        if ($dsn['password']) {
            $params[0] .= ' password=\'' . addslashes($dsn['password']) . '\'';
        }
        if (!empty($dsn['options'])) {
            $params[0] .= ' options=' . $dsn['options'];
        }
        if (!empty($dsn['tty'])) {
            $params[0] .= ' tty=' . $dsn['tty'];
        }
        if (!empty($dsn['connect_timeout'])) {
            $params[0] .= ' connect_timeout=' . $dsn['connect_timeout'];
        }
        if (!empty($dsn['sslmode'])) {
            $params[0] .= ' sslmode=' . $dsn['sslmode'];
        }
        if (!empty($dsn['service'])) {
            $params[0] .= ' service=' . $dsn['service'];
        }

        if (isset($dsn['new_link'])
            && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true)) {
            if (version_compare(phpversion(), '4.3.0', '>=')) {
                $params[] = PGSQL_CONNECT_FORCE_NEW;
            }
        }

        $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';

        $ini = ini_get('track_errors');
        $php_errormsg = '';
        if ($ini) {
            $this->connection = @call_user_func_array(
                $connect_function,
                $params
            );
        } else {
            @ini_set('track_errors', 1);
            $this->connection = @call_user_func_array(
                $connect_function,
                $params
            );
            @ini_set('track_errors', $ini);
        }

        if (!$this->connection) {
            return $this->raiseError(
                DB_ERROR_CONNECT_FAILED,
                null,
                null,
                null,
                $php_errormsg
            );
        }
        return DB_OK;
    }

    // }}}
    // {{{ disconnect()

    /**
     * Disconnects from the database server
     *
     * @return bool  TRUE on success, FALSE on failure
     */
    public function disconnect()
    {
        $ret = @pg_close($this->connection);
        $this->connection = null;
        return $ret;
    }

    // }}}
    // {{{ simpleQuery()

    /**
     * Sends a query to the database server
     *
     * @param string  the SQL query string
     *
     * @return mixed  + a PHP result resrouce for successful SELECT queries
     *                + the DB_OK constant for other successful queries
     *                + a DB_Error object on failure
     */
    public function simpleQuery($query)
    {
        $ismanip = $this->_checkManip($query);
        $this->last_query = $query;
        $query = $this->modifyQuery($query);
        if (!$this->autocommit && $ismanip) {
            if ($this->transaction_opcount == 0) {
                $result = @pg_exec($this->connection, 'begin;');
                if (!$result) {
                    return $this->pgsqlRaiseError();
                }
            }
            $this->transaction_opcount++;
        }
        $result = @pg_exec($this->connection, $query);
        if (!$result) {
            return $this->pgsqlRaiseError();
        }

        /*
         * Determine whether queries produce affected rows, result or nothing.
         *
         * This logic was introduced in version 1.1 of the file by ssb,
         * though the regex has been modified slightly since then.
         *
         * PostgreSQL commands:
         * ABORT, ALTER, BEGIN, CLOSE, CLUSTER, COMMIT, COPY,
         * CREATE, DECLARE, DELETE, DROP TABLE, EXPLAIN, FETCH,
         * GRANT, INSERT, LISTEN, LOAD, LOCK, MOVE, NOTIFY, RESET,
         * REVOKE, ROLLBACK, SELECT, SELECT INTO, SET, SHOW,
         * UNLISTEN, UPDATE, VACUUM, WITH
         */
        if ($ismanip) {
            $this->affected = @pg_affected_rows($result);
            return DB_OK;
        } elseif (preg_match(
            '/^\s*\(*\s*(SELECT|EXPLAIN|FETCH|SHOW|WITH)\s/si',
            $query
        )) {
            $this->row[(int)$result] = 0; // reset the row counter.
            $numrows = $this->numRows($result);
            if (is_object($numrows)) {
                return $numrows;
            }
            $this->_num_rows[(int)$result] = $numrows;
            $this->affected = 0;
            return $result;
        } else {
            $this->affected = 0;
            return DB_OK;
        }
    }

    // }}}
    // {{{ nextResult()

    /**
     * Checks if the given query is a manipulation query. This also takes into
     * account the _next_query_manip flag and sets the _last_query_manip flag
     * (and resets _next_query_manip) according to the result.
     *
     * @param string The query to check.
     *
     * @return boolean true if the query is a manipulation query, false
     * otherwise
     *
     * @access protected
     */
    public function _checkManip($query)
    {
        return (preg_match('/^\s*(SAVEPOINT|RELEASE)\s+/i', $query)
            || parent::_checkManip($query));
    }

    // }}}
    // {{{ fetchInto()

    /**
     * Produces a DB_Error object regarding the current problem
     *
     * @param int $errno if the error is being manually raised pass a
     *                     DB_ERROR* constant here.  If this isn't passed
     *                     the error information gathered from the DBMS.
     *
     * @return object  the DB_Error object
     *
     * @see DB_common::raiseError(),
     *      DB_pgsql::errorNative(), DB_pgsql::errorCode()
     */
    public function pgsqlRaiseError($errno = null)
    {
        $native = $this->errorNative();
        if (!$native) {
            $native = 'Database connection has been lost.';
            $errno = DB_ERROR_CONNECT_FAILED;
        }
        if ($errno === null) {
            $errno = $this->errorCode($native);
        }
        return $this->raiseError($errno, null, null, null, $native);
    }

    // }}}
    // {{{ freeResult()

    /**
     * Gets the DBMS' native error message produced by the last query
     *
     * {@internal Error messages are used instead of error codes
     * in order to support older versions of PostgreSQL.}}
     *
     * @return string  the DBMS' error message
     */
    public function errorNative()
    {
        return @pg_errormessage($this->connection);
    }

    // }}}
    // {{{ quoteBoolean()

    /**
     * Determines PEAR::DB error code from the database's text error message.
     *
     * @param string $errormsg error message returned from the database
     * @return integer  an error number from a DB error constant
     */
    public function errorCode($errormsg)
    {
        static $error_regexps;
        if (!isset($error_regexps)) {
            $error_regexps = array(
                '/column .* (of relation .*)?does not exist/i'
                => DB_ERROR_NOSUCHFIELD,
                '/(relation|sequence|table).*does not exist|class .* not found/i'
                => DB_ERROR_NOSUCHTABLE,
                '/index .* does not exist/'
                => DB_ERROR_NOT_FOUND,
                '/relation .* already exists/i'
                => DB_ERROR_ALREADY_EXISTS,
                '/(divide|division) by zero$/i'
                => DB_ERROR_DIVZERO,
                '/pg_atoi: error in .*: can\'t parse /i'
                => DB_ERROR_INVALID_NUMBER,
                '/invalid input syntax for( type)? (integer|numeric)/i'
                => DB_ERROR_INVALID_NUMBER,
                '/value .* is out of range for type \w*int/i'
                => DB_ERROR_INVALID_NUMBER,
                '/integer out of range/i'
                => DB_ERROR_INVALID_NUMBER,
                '/value too long for type character/i'
                => DB_ERROR_INVALID,
                '/attribute .* not found|relation .* does not have attribute/i'
                => DB_ERROR_NOSUCHFIELD,
                '/column .* specified in USING clause does not exist in (left|right) table/i'
                => DB_ERROR_NOSUCHFIELD,
                '/parser: parse error at or near/i'
                => DB_ERROR_SYNTAX,
                '/syntax error at/'
                => DB_ERROR_SYNTAX,
                '/column reference .* is ambiguous/i'
                => DB_ERROR_SYNTAX,
                '/permission denied/'
                => DB_ERROR_ACCESS_VIOLATION,
                '/violates not-null constraint/'
                => DB_ERROR_CONSTRAINT_NOT_NULL,
                '/violates [\w ]+ constraint/'
                => DB_ERROR_CONSTRAINT,
                '/referential integrity violation/'
                => DB_ERROR_CONSTRAINT,
                '/more expressions than target columns/i'
                => DB_ERROR_VALUE_COUNT_ON_ROW,
            );
        }
        foreach ($error_regexps as $regexp => $code) {
            if (preg_match($regexp, $errormsg)) {
                return $code;
            }
        }
        // Fall back to DB_ERROR if there was no mapping.
        return DB_ERROR;
    }

    // }}}
    // {{{ escapeSimple()

    /**
     * Gets the number of rows in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numRows() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result PHP's query result resource
     *
     * @return int|object
     *
     * @see DB_result::numRows()
     */
    public function numRows($result)
    {
        $rows = @pg_numrows($result);
        if ($rows === null) {
            return $this->pgsqlRaiseError();
        }
        return $rows;
    }

    // }}}
    // {{{ numCols()

    /**
     * Move the internal pgsql result pointer to the next available result
     *
     * @param a valid fbsql result resource
     *
     * @access public
     *
     * @return true if a result is available otherwise return false
     */
    public function nextResult($result)
    {
        return false;
    }

    // }}}
    // {{{ numRows()

    /**
     * Places a row from the result set into the given array
     *
     * Formating of the array and the data therein are configurable.
     * See DB_result::fetchInto() for more information.
     *
     * This method is not meant to be called directly.  Use
     * DB_result::fetchInto() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result the query result resource
     * @param array $arr the referenced array to put the data in
     * @param int $fetchmode how the resulting array should be indexed
     * @param int $rownum the row number to fetch (0 = first row)
     *
     * @return mixed  DB_OK on success, NULL when the end of a result set is
     *                 reached or on failure
     *
     * @see DB_result::fetchInto()
     */
    public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
    {
        $result_int = (int)$result;
        $rownum = ($rownum !== null) ? $rownum : $this->row[$result_int];
        if ($rownum >= $this->_num_rows[$result_int]) {
            return null;
        }
        if ($fetchmode & DB_FETCHMODE_ASSOC) {
            $arr = @pg_fetch_array($result, $rownum, PGSQL_ASSOC);
            if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
                $arr = array_change_key_case($arr, CASE_LOWER);
            }
        } else {
            $arr = @pg_fetch_row($result, $rownum);
        }
        if (!$arr) {
            return null;
        }
        if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
            $this->_rtrimArrayValues($arr);
        }
        if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
            $this->_convertNullArrayValuesToEmpty($arr);
        }
        $this->row[$result_int] = ++$rownum;
        return DB_OK;
    }

    // }}}
    // {{{ autoCommit()

    /**
     * Deletes the result set and frees the memory occupied by the result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::free() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result PHP's query result resource
     *
     * @return bool  TRUE on success, FALSE if $result is invalid
     *
     * @see DB_result::free()
     */
    public function freeResult($result)
    {
        if (is_resource($result)) {
            unset($this->row[(int)$result]);
            unset($this->_num_rows[(int)$result]);
            $this->affected = 0;
            return @pg_freeresult($result);
        }
        return false;
    }

    // }}}
    // {{{ commit()

    /**
     * Formats a boolean value for use within a query in a locale-independent
     * manner.
     *
     * @param boolean the boolean value to be quoted.
     * @return string the quoted string.
     * @see DB_common::quoteSmart()
     * @since Method available since release 1.7.8.
     */
    public function quoteBoolean($boolean)
    {
        return $boolean ? 'TRUE' : 'FALSE';
    }

    // }}}
    // {{{ rollback()

    /**
     * Escapes a string according to the current DBMS's standards
     *
     * {@internal PostgreSQL treats a backslash as an escape character,
     * so they are escaped as well.
     *
     * @param string $str the string to be escaped
     *
     * @return string  the escaped string
     *
     * @see DB_common::quoteSmart()
     * @since Method available since Release 1.6.0
     */
    public function escapeSimple($str)
    {
        if (function_exists('pg_escape_string')) {
            /* This fixes an undocumented BC break in PHP 5.2.0 which changed
             * the prototype of pg_escape_string. I'm not thrilled about having
             * to sniff the PHP version, quite frankly, but it's the only way
             * to deal with the problem. Revision 1.331.2.13.2.10 on
             * php-src/ext/pgsql/pgsql.c (PHP_5_2 branch) is to blame, for the
             * record. */
            if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
                return pg_escape_string($this->connection, $str);
            } else {
                return pg_escape_string($str);
            }
        } else {
            return str_replace("'", "''", str_replace('\\', '\\\\', $str));
        }
    }

    // }}}
    // {{{ affectedRows()

    /**
     * Gets the number of columns in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numCols() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result PHP's query result resource
     *
     * @return int|object
     *
     * @see DB_result::numCols()
     */
    public function numCols($result)
    {
        $cols = @pg_numfields($result);
        if (!$cols) {
            return $this->pgsqlRaiseError();
        }
        return $cols;
    }

    // }}}
    // {{{ nextId()

    /**
     * Enables or disables automatic commits
     *
     * @param bool $onoff true turns it on, false turns it off
     *
     * @return int  DB_OK on success.  A DB_Error object if the driver
     *               doesn't support auto-committing transactions.
     */
    public function autoCommit($onoff = false)
    {
        // XXX if $this->transaction_opcount > 0, we should probably
        // issue a warning here.
        $this->autocommit = $onoff ? true : false;
        return DB_OK;
    }

    // }}}
    // {{{ createSequence()

    /**
     * Commits the current transaction
     *
     * @return int|object
     */
    public function commit()
    {
        if ($this->transaction_opcount > 0) {
            // (disabled) hack to shut up error messages from libpq.a
            //@fclose(@fopen("php://stderr", "w"));
            $result = @pg_exec($this->connection, 'end;');
            $this->transaction_opcount = 0;
            if (!$result) {
                return $this->pgsqlRaiseError();
            }
        }
        return DB_OK;
    }

    // }}}
    // {{{ dropSequence()

    /**
     * Reverts the current transaction
     *
     * @return int|object
     */
    public function rollback()
    {
        if ($this->transaction_opcount > 0) {
            $result = @pg_exec($this->connection, 'abort;');
            $this->transaction_opcount = 0;
            if (!$result) {
                return $this->pgsqlRaiseError();
            }
        }
        return DB_OK;
    }

    // }}}
    // {{{ modifyLimitQuery()

    /**
     * Determines the number of rows affected by a data maniuplation query
     *
     * 0 is returned for queries that don't manipulate data.
     *
     * @return int  the number of rows.  A DB_Error object on failure.
     */
    public function affectedRows()
    {
        return $this->affected;
    }

    // }}}
    // {{{ pgsqlRaiseError()

    /**
     * Returns the next free id in a sequence
     *
     * @param string $seq_name name of the sequence
     * @param boolean $ondemand when true, the seqence is automatically
     *                            created if it does not exist
     *
     * @return int|object
     *               A DB_Error object on failure.
     *
     * @see DB_common::nextID(), DB_common::getSequenceName(),
     *      DB_pgsql::createSequence(), DB_pgsql::dropSequence()
     */
    public function nextId($seq_name, $ondemand = true)
    {
        $seqname = $this->getSequenceName($seq_name);
        $repeat = false;
        do {
            $this->pushErrorHandling(PEAR_ERROR_RETURN);
            $result = $this->query("SELECT NEXTVAL('${seqname}')");
            $this->popErrorHandling();
            if ($ondemand && DB::isError($result) &&
                $result->getCode() == DB_ERROR_NOSUCHTABLE) {
                $repeat = true;
                $this->pushErrorHandling(PEAR_ERROR_RETURN);
                $result = $this->createSequence($seq_name);
                $this->popErrorHandling();
                if (DB::isError($result)) {
                    return $this->raiseError($result);
                }
            } else {
                $repeat = false;
            }
        } while ($repeat);
        if (DB::isError($result)) {
            return $this->raiseError($result);
        }
        $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
        $result->free();
        return $arr[0];
    }

    // }}}
    // {{{ errorNative()

    /**
     * Creates a new sequence
     *
     * @param string $seq_name name of the new sequence
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::createSequence(), DB_common::getSequenceName(),
     *      DB_pgsql::nextID(), DB_pgsql::dropSequence()
     */
    public function createSequence($seq_name)
    {
        $seqname = $this->getSequenceName($seq_name);
        $result = $this->query("CREATE SEQUENCE ${seqname}");
        return $result;
    }

    // }}}
    // {{{ errorCode()

    /**
     * Deletes a sequence
     *
     * @param string $seq_name name of the sequence to be deleted
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::dropSequence(), DB_common::getSequenceName(),
     *      DB_pgsql::nextID(), DB_pgsql::createSequence()
     */
    public function dropSequence($seq_name)
    {
        return $this->query('DROP SEQUENCE '
            . $this->getSequenceName($seq_name));
    }

    // }}}
    // {{{ tableInfo()

    /**
     * Adds LIMIT clauses to a query string according to current DBMS standards
     *
     * @param string $query the query to modify
     * @param int $from the row to start to fetching (0 = the first row)
     * @param int $count the numbers of rows to fetch
     * @param mixed $params array, string or numeric data to be used in
     *                         execution of the statement.  Quantity of items
     *                         passed must match quantity of placeholders in
     *                         query:  meaning 1 placeholder for non-array
     *                         parameters or 1 placeholder per array element.
     *
     * @return string  the query string with LIMIT clauses added
     *
     * @access protected
     */
    public function modifyLimitQuery($query, $from, $count, $params = array())
    {
        return "$query LIMIT $count OFFSET $from";
    }

    // }}}
    // {{{ _pgFieldFlags()

    /**
     * Returns information about a table or a result set
     *
     * NOTE: only supports 'table' and 'flags' if <var>$result</var>
     * is a table name.
     *
     * @param object|string $result DB_result object from a query or a
     *                                 string containing the name of a table.
     *                                 While this also accepts a query result
     *                                 resource identifier, this behavior is
     *                                 deprecated.
     * @param int $mode a valid tableInfo mode
     *
     * @return array|object
     *                 A DB_Error object on failure.
     *
     * @see DB_common::tableInfo()
     */
    public function tableInfo($result, $mode = null)
    {
        if (is_string($result)) {
            /*
             * Probably received a table name.
             * Create a result resource identifier.
             */
            $id = @pg_exec($this->connection, "SELECT * FROM $result LIMIT 0");
            $got_string = true;
        } elseif (isset($result->result)) {
            /*
             * Probably received a result object.
             * Extract the result resource identifier.
             */
            $id = $result->result;
            $got_string = false;
        } else {
            /*
             * Probably received a result resource identifier.
             * Copy it.
             * Deprecated.  Here for compatibility only.
             */
            $id = $result;
            $got_string = false;
        }

        if (!is_resource($id)) {
            return $this->pgsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
        }

        if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
            $case_func = 'strtolower';
        } else {
            $case_func = 'strval';
        }

        $count = @pg_numfields($id);
        $res = array();

        if ($mode) {
            $res['num_fields'] = $count;
        }

        for ($i = 0; $i < $count; $i++) {
            $res[$i] = array(
                'table' => $got_string ? $case_func($result) : '',
                'name' => $case_func(@pg_fieldname($id, $i)),
                'type' => @pg_fieldtype($id, $i),
                'len' => @pg_fieldsize($id, $i),
                'flags' => $got_string
                    ? $this->_pgFieldFlags($id, $i, $result)
                    : '',
            );
            if ($mode & DB_TABLEINFO_ORDER) {
                $res['order'][$res[$i]['name']] = $i;
            }
            if ($mode & DB_TABLEINFO_ORDERTABLE) {
                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
            }
        }

        // free the result only if we were called on a table
        if ($got_string) {
            @pg_freeresult($id);
        }
        return $res;
    }

    // }}}
    // {{{ getSpecialQuery()

    /**
     * Get a column's flags
     *
     * Supports "not_null", "default_value", "primary_key", "unique_key"
     * and "multiple_key".  The default value is passed through
     * rawurlencode() in case there are spaces in it.
     *
     * @param int $resource the PostgreSQL result identifier
     * @param int $num_field the field number
     *
     * @param $table_name
     * @return string  the flags
     *
     * @access private
     */
    public function _pgFieldFlags($resource, $num_field, $table_name)
    {
        $field_name = @pg_fieldname($resource, $num_field);

        // Check if there's a schema in $table_name and update things
        // accordingly.
        $from = 'pg_attribute f, pg_class tab, pg_type typ';
        if (strpos($table_name, '.') !== false) {
            $from .= ', pg_namespace nsp';
            list($schema, $table) = explode('.', $table_name);
            $tableWhere = "tab.relname = '$table' AND tab.relnamespace = nsp.oid AND nsp.nspname = '$schema'";
        } else {
            $tableWhere = "tab.relname = '$table_name'";
        }

        $result = @pg_exec($this->connection, "SELECT f.attnotnull, f.atthasdef
                                FROM $from
                                WHERE tab.relname = typ.typname
                                AND typ.typrelid = f.attrelid
                                AND f.attname = '$field_name'
                                AND $tableWhere");
        if (@pg_numrows($result) > 0) {
            $row = @pg_fetch_row($result, 0);
            $flags = ($row[0] == 't') ? 'not_null ' : '';

            if ($row[1] == 't') {
                $result = @pg_exec($this->connection, "SELECT a.adsrc
                                    FROM $from, pg_attrdef a
                                    WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
                                    AND f.attrelid = a.adrelid AND f.attname = '$field_name'
                                    AND $tableWhere AND f.attnum = a.adnum");
                $row = @pg_fetch_row($result, 0);
                $num = preg_replace("/'(.*)'::\w+/", "\\1", $row[0]);
                $flags .= 'default_' . rawurlencode($num) . ' ';
            }
        } else {
            $flags = '';
        }
        $result = @pg_exec($this->connection, "SELECT i.indisunique, i.indisprimary, i.indkey
                                FROM $from, pg_index i
                                WHERE tab.relname = typ.typname
                                AND typ.typrelid = f.attrelid
                                AND f.attrelid = i.indrelid
                                AND f.attname = '$field_name'
                                AND $tableWhere");
        $count = @pg_numrows($result);

        for ($i = 0; $i < $count; $i++) {
            $row = @pg_fetch_row($result, $i);
            $keys = explode(' ', $row[2]);

            if (in_array($num_field + 1, $keys)) {
                $flags .= ($row[0] == 't' && $row[1] == 'f') ? 'unique_key ' : '';
                $flags .= ($row[1] == 't') ? 'primary_key ' : '';
                if (count($keys) > 1) {
                    $flags .= 'multiple_key ';
                }
            }
        }

        return trim($flags);
    }

    // }}}
    // {{{ _checkManip()

    /**
     * Obtains the query string needed for listing a given type of objects
     *
     * @param string $type the kind of objects you want to retrieve
     *
     * @return string  the SQL query string or null if the driver doesn't
     *                  support the object type requested
     *
     * @access protected
     * @see DB_common::getListOf()
     */
    public function getSpecialQuery($type)
    {
        switch ($type) {
            case 'tables':
                return 'SELECT c.relname AS "Name"'
                    . ' FROM pg_class c, pg_user u'
                    . ' WHERE c.relowner = u.usesysid'
                    . " AND c.relkind = 'r'"
                    . ' AND NOT EXISTS'
                    . ' (SELECT 1 FROM pg_views'
                    . '  WHERE viewname = c.relname)'
                    . " AND c.relname !~ '^(pg_|sql_)'"
                    . ' UNION'
                    . ' SELECT c.relname AS "Name"'
                    . ' FROM pg_class c'
                    . " WHERE c.relkind = 'r'"
                    . ' AND NOT EXISTS'
                    . ' (SELECT 1 FROM pg_views'
                    . '  WHERE viewname = c.relname)'
                    . ' AND NOT EXISTS'
                    . ' (SELECT 1 FROM pg_user'
                    . '  WHERE usesysid = c.relowner)'
                    . " AND c.relname !~ '^pg_'";
            case 'schema.tables':
                return "SELECT schemaname || '.' || tablename"
                    . ' AS "Name"'
                    . ' FROM pg_catalog.pg_tables'
                    . ' WHERE schemaname NOT IN'
                    . " ('pg_catalog', 'information_schema', 'pg_toast')";
            case 'schema.views':
                return "SELECT schemaname || '.' || viewname from pg_views WHERE schemaname"
                    . " NOT IN ('information_schema', 'pg_catalog')";
            case 'views':
                // Table cols: viewname | viewowner | definition
                return 'SELECT viewname from pg_views WHERE schemaname'
                    . " NOT IN ('information_schema', 'pg_catalog')";
            case 'users':
                // cols: usename |usesysid|usecreatedb|usetrace|usesuper|usecatupd|passwd  |valuntil
                return 'SELECT usename FROM pg_user';
            case 'databases':
                return 'SELECT datname FROM pg_database';
            case 'functions':
            case 'procedures':
                return 'SELECT proname FROM pg_proc WHERE proowner <> 1';
            default:
                return null;
        }
    }
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */


code:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * The PEAR DB driver for PHP's sqlite extension
 * for interacting with SQLite databases
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Database
 * @package    DB
 * @author     Urs Gehrig <urs@circle.ch>
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  1997-2007 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0 3.0
 * @version    CVS: $Id$
 * @link       http://pear.php.net/package/DB
 */

/**
 * Obtain the DB_common class so it can be extended from
 */
//require_once 'DB/common.php';
require_once 'common.php';

/**
 * The methods PEAR DB uses to interact with PHP's sqlite extension
 * for interacting with SQLite databases
 *
 * These methods overload the ones declared in DB_common.
 *
 * NOTICE:  This driver needs PHP's track_errors ini setting to be on.
 * It is automatically turned on when connecting to the database.
 * Make sure your scripts don't turn it off.
 *
 * @category   Database
 * @package    DB
 * @author     Urs Gehrig <urs@circle.ch>
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  1997-2007 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0 3.0
 * @version    Release: 1.9.2
 * @link       http://pear.php.net/package/DB
 */
class DB_sqlite extends DB_common
{
    // {{{ properties

    /**
     * The DB driver type (mysql, oci8, odbc, etc.)
     * @var string
     */
    public $phptype = 'sqlite';

    /**
     * The database syntax variant to be used (db2, access, etc.), if any
     * @var string
     */
    public $dbsyntax = 'sqlite';

    /**
     * The capabilities of this DB implementation
     *
     * The 'new_link' element contains the PHP version that first provided
     * new_link support for this DBMS.  Contains false if it's unsupported.
     *
     * Meaning of the 'limit' element:
     *   + 'emulate' = emulate with fetch row by number
     *   + 'alter'   = alter the query
     *   + false     = skip rows
     *
     * @var array
     */
    public $features = array(
        'limit' => 'alter',
        'new_link' => false,
        'numrows' => true,
        'pconnect' => true,
        'prepare' => false,
        'ssl' => false,
        'transactions' => false,
    );

    /**
     * A mapping of native error codes to DB error codes
     *
     * {@internal  Error codes according to sqlite_exec.  See the online
     * manual at http://sqlite.org/c_interface.html for info.
     * This error handling based on sqlite_exec is not yet implemented.}}
     *
     * @var array
     */
    public $errorcode_map = array();

    /**
     * The raw database connection created by PHP
     * @var resource
     */
    public $connection;

    /**
     * The DSN information for connecting to a database
     * @var array
     */
    public $dsn = array();

    /**
     * SQLite data types
     *
     * @link http://www.sqlite.org/datatypes.html
     *
     * @var array
     */
    public $keywords = array(
        'BLOB' => '',
        'BOOLEAN' => '',
        'CHARACTER' => '',
        'CLOB' => '',
        'FLOAT' => '',
        'INTEGER' => '',
        'KEY' => '',
        'NATIONAL' => '',
        'NUMERIC' => '',
        'NVARCHAR' => '',
        'PRIMARY' => '',
        'TEXT' => '',
        'TIMESTAMP' => '',
        'UNIQUE' => '',
        'VARCHAR' => '',
        'VARYING' => '',
    );

    /**
     * The most recent error message from $php_errormsg
     * @var string
     * @access private
     */
    public $_lasterror = '';

    // }}}
    // {{{ constructor

    /**
     * This constructor calls parent::__construct()
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    // }}}
    // {{{ connect()

    /**
     * Connect to the database server, log in and open the database
     *
     * Don't call this method directly.  Use DB::connect() instead.
     *
     * PEAR DB's sqlite driver supports the following extra DSN options:
     *   + mode  The permissions for the database file, in four digit
     *            chmod octal format (eg "0600").
     *
     * Example of connecting to a database in read-only mode:
     *
     * require_once 'DB.php';
     *
     * $dsn = 'sqlite:///path/and/name/of/db/file?mode=0400';
     * $options = array(
     *     'portability' => DB_PORTABILITY_ALL,
     * );
     *
     * $db = DB::connect($dsn, $options);
     * if ((new PEAR)->isError($db)) {
     *     die($db->getMessage());
     * }
     *
     *
     * @param array $dsn the data source name
     * @param bool $persistent should the connection be persistent?
     *
     * @return int|object
     */
    public function connect($dsn, $persistent = false)
    {
        if (!PEAR::loadExtension('sqlite')) {
            return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
        }

        $this->dsn = $dsn;
        if ($dsn['dbsyntax']) {
            $this->dbsyntax = $dsn['dbsyntax'];
        }

        if (!$dsn['database']) {
            return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
        }

        if ($dsn['database'] !== ':memory:') {
            if (!file_exists($dsn['database'])) {
                if (!touch($dsn['database'])) {
                    return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
                }
                if (!isset($dsn['mode']) ||
                    !is_numeric($dsn['mode'])) {
                    $mode = 0644;
                } else {
                    $mode = octdec($dsn['mode']);
                }
                if (!chmod($dsn['database'], $mode)) {
                    return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
                }
                if (!file_exists($dsn['database'])) {
                    return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
                }
            }
            if (!is_file($dsn['database'])) {
                return $this->sqliteRaiseError(DB_ERROR_INVALID);
            }
            if (!is_readable($dsn['database'])) {
                return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
            }
        }

        $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';

        // track_errors must remain on for simpleQuery()
        @ini_set('track_errors', 1);
        $php_errormsg = '';

        if (!$this->connection = @$connect_function($dsn['database'])) {
            return $this->raiseError(
                DB_ERROR_NODBSELECTED,
                null,
                null,
                null,
                $php_errormsg
            );
        }
        return DB_OK;
    }

    // }}}
    // {{{ disconnect()

    /**
     * Produces a DB_Error object regarding the current problem
     *
     * @param int $errno if the error is being manually raised pass a
     *                     DB_ERROR* constant here.  If this isn't passed
     *                     the error information gathered from the DBMS.
     *
     * @return object  the DB_Error object
     *
     * @see DB_common::raiseError(),
     *      DB_sqlite::errorNative(), DB_sqlite::errorCode()
     */
    public function sqliteRaiseError($errno = null)
    {
        $native = $this->errorNative();
        if ($errno === null) {
            $errno = $this->errorCode($native);
        }

        $errorcode = @sqlite_last_error($this->connection);
        $userinfo = "$errorcode ** $this->last_query";

        return $this->raiseError($errno, null, null, $userinfo, $native);
    }

    // }}}
    // {{{ simpleQuery()

    /**
     * Gets the DBMS' native error message produced by the last query
     *
     * {@internal This is used to retrieve more meaningfull error messages
     * because sqlite_last_error() does not provide adequate info.}}
     *
     * @return string  the DBMS' error message
     */
    public function errorNative()
    {
        return $this->_lasterror;
    }

    // }}}
    // {{{ nextResult()

    /**
     * Determines PEAR::DB error code from the database's text error message
     *
     * @param string $errormsg the error message returned from the database
     *
     * @return integer  the DB error number
     */
    public function errorCode($errormsg)
    {
        static $error_regexps;

        // PHP 5.2+ prepends the function name to $php_errormsg, so we need
        // this hack to work around it, per bug #9599.
        $errormsg = preg_replace('/^sqlite[a-z_]+\(\): /', '', $errormsg);

        if (!isset($error_regexps)) {
            $error_regexps = array(
                '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
                '/^no such index:/' => DB_ERROR_NOT_FOUND,
                '/^(table|index) .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
                '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
                '/is not unique/' => DB_ERROR_CONSTRAINT,
                '/columns .* are not unique/i' => DB_ERROR_CONSTRAINT,
                '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
                '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
                '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
                '/no column named/' => DB_ERROR_NOSUCHFIELD,
                '/column not present in both tables/i' => DB_ERROR_NOSUCHFIELD,
                '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX,
                '/[0-9]+ values for [0-9]+ columns/i' => DB_ERROR_VALUE_COUNT_ON_ROW,
            );
        }
        foreach ($error_regexps as $regexp => $code) {
            if (preg_match($regexp, $errormsg)) {
                return $code;
            }
        }
        // Fall back to DB_ERROR if there was no mapping.
        return DB_ERROR;
    }

    // }}}
    // {{{ fetchInto()

    /**
     * Disconnects from the database server
     *
     * @return bool|void
     */
    public function disconnect()
    {
        $ret = @sqlite_close($this->connection);
        $this->connection = null;
        return $ret;
    }

    // }}}
    // {{{ freeResult()

    /**
     * Sends a query to the database server
     *
     * NOTICE:  This method needs PHP's track_errors ini setting to be on.
     * It is automatically turned on when connecting to the database.
     * Make sure your scripts don't turn it off.
     *
     * @param string  the SQL query string
     *
     * @return mixed  + a PHP result resrouce for successful SELECT queries
     *                + the DB_OK constant for other successful queries
     *                + a DB_Error object on failure
     */
    public function simpleQuery($query)
    {
        $ismanip = $this->_checkManip($query);
        $this->last_query = $query;
        $query = $this->modifyQuery($query);

        $php_errormsg = '';

        $result = @sqlite_query($query, $this->connection);
        $this->_lasterror = $php_errormsg ? $php_errormsg : '';

        $this->result = $result;
        if (!$this->result) {
            return $this->sqliteRaiseError(null);
        }

        // sqlite_query() seems to allways return a resource
        // so cant use that. Using $ismanip instead
        if (!$ismanip) {
            $numRows = $this->numRows($result);
            if (is_object($numRows)) {
                // we've got PEAR_Error
                return $numRows;
            }
            return $result;
        }
        return DB_OK;
    }

    // }}}
    // {{{ numCols()

    /**
     * Changes a query string for various DBMS specific reasons
     *
     * This little hack lets you know how many rows were deleted
     * when running a "DELETE FROM table" query.  Only implemented
     * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
     *
     * @param string $query the query string to modify
     *
     * @return string  the modified query string
     *
     * @access protected
     * @see DB_common::setOption()
     */
    public function modifyQuery($query)
    {
        if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
                $query = preg_replace(
                    '/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
                    'DELETE FROM \1 WHERE 1=1',
                    $query
                );
            }
        }
        return $query;
    }

    // }}}
    // {{{ numRows()

    /**
     * Gets the number of rows in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numRows() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result PHP's query result resource
     *
     * @return int|object
     *
     * @see DB_result::numRows()
     */
    public function numRows($result)
    {
        $rows = @sqlite_num_rows($result);
        if ($rows === null) {
            return $this->sqliteRaiseError();
        }
        return $rows;
    }

    // }}}
    // {{{ affected()

    /**
     * Move the internal sqlite result pointer to the next available result
     *
     * @param resource $result the valid sqlite result resource
     *
     * @return bool  true if a result is available otherwise return false
     */
    public function nextResult($result)
    {
        return false;
    }

    // }}}
    // {{{ dropSequence()

    /**
     * Places a row from the result set into the given array
     *
     * Formating of the array and the data therein are configurable.
     * See DB_result::fetchInto() for more information.
     *
     * This method is not meant to be called directly.  Use
     * DB_result::fetchInto() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result the query result resource
     * @param array $arr the referenced array to put the data in
     * @param int $fetchmode how the resulting array should be indexed
     * @param int $rownum the row number to fetch (0 = first row)
     *
     * @return mixed  DB_OK on success, NULL when the end of a result set is
     *                 reached or on failure
     *
     * @see DB_result::fetchInto()
     */
    public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
    {
        if ($rownum !== null) {
            if (!@sqlite_seek($this->result, $rownum)) {
                return null;
            }
        }
        if ($fetchmode & DB_FETCHMODE_ASSOC) {
            $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
            if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
                $arr = array_change_key_case($arr, CASE_LOWER);
            }

            /* Remove extraneous " characters from the fields in the result.
             * Fixes bug #11716. */
            if (is_array($arr) && count($arr) > 0) {
                $strippedArr = array();
                foreach ($arr as $field => $value) {
                    $strippedArr[trim($field, '"')] = $value;
                }
                $arr = $strippedArr;
            }
        } else {
            $arr = @sqlite_fetch_array($result, SQLITE_NUM);
        }
        if (!$arr) {
            return null;
        }
        if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
            /*
             * Even though this DBMS already trims output, we do this because
             * a field might have intentional whitespace at the end that
             * gets removed by DB_PORTABILITY_RTRIM under another driver.
             */
            $this->_rtrimArrayValues($arr);
        }
        if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
            $this->_convertNullArrayValuesToEmpty($arr);
        }
        return DB_OK;
    }

    /**
     * Deletes the result set and frees the memory occupied by the result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::free() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result PHP's query result resource
     *
     * @return bool  TRUE on success, FALSE if $result is invalid
     *
     * @see DB_result::free()
     */
    public function freeResult(&$result)
    {
        // XXX No native free?
        if (!is_resource($result)) {
            return false;
        }
        $result = null;
        return true;
    }

    // }}}
    // {{{ nextId()

    /**
     * Gets the number of columns in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numCols() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result PHP's query result resource
     *
     * @return int|object
     *
     * @see DB_result::numCols()
     */
    public function numCols($result)
    {
        $cols = @sqlite_num_fields($result);
        if (!$cols) {
            return $this->sqliteRaiseError();
        }
        return $cols;
    }

    // }}}
    // {{{ getDbFileStats()

    /**
     * Determines the number of rows affected by a data maniuplation query
     *
     * 0 is returned for queries that don't manipulate data.
     *
     * @return int  the number of rows.  A DB_Error object on failure.
     */
    public function affectedRows()
    {
        return @sqlite_changes($this->connection);
    }

    // }}}
    // {{{ escapeSimple()

    /**
     * Deletes a sequence
     *
     * @param string $seq_name name of the sequence to be deleted
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::dropSequence(), DB_common::getSequenceName(),
     *      DB_sqlite::nextID(), DB_sqlite::createSequence()
     */
    public function dropSequence($seq_name)
    {
        return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
    }

    // }}}
    // {{{ modifyLimitQuery()

    /**
     * Returns the next free id in a sequence
     *
     * @param string $seq_name name of the sequence
     * @param boolean $ondemand when true, the seqence is automatically
     *                            created if it does not exist
     *
     * @return int|object
     *               A DB_Error object on failure.
     *
     * @see DB_common::nextID(), DB_common::getSequenceName(),
     *      DB_sqlite::createSequence(), DB_sqlite::dropSequence()
     */
    public function nextId($seq_name, $ondemand = true)
    {
        $seqname = $this->getSequenceName($seq_name);

        do {
            $repeat = 0;
            $this->pushErrorHandling(PEAR_ERROR_RETURN);
            $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)");
            $this->popErrorHandling();
            if ($result === DB_OK) {
                $id = @sqlite_last_insert_rowid($this->connection);
                if ($id != 0) {
                    return $id;
                }
            } elseif ($ondemand && DB::isError($result) &&
                $result->getCode() == DB_ERROR_NOSUCHTABLE) {
                $result = $this->createSequence($seq_name);
                if (DB::isError($result)) {
                    return $this->raiseError($result);
                } else {
                    $repeat = 1;
                }
            }
        } while ($repeat);

        return $this->raiseError($result);
    }

    // }}}
    // {{{ modifyQuery()

    /**
     * Creates a new sequence
     *
     * @param string $seq_name name of the new sequence
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::createSequence(), DB_common::getSequenceName(),
     *      DB_sqlite::nextID(), DB_sqlite::dropSequence()
     */
    public function createSequence($seq_name)
    {
        $seqname = $this->getSequenceName($seq_name);
        $query = 'CREATE TABLE ' . $seqname .
            ' (id INTEGER UNSIGNED PRIMARY KEY) ';
        $result = $this->query($query);
        if (DB::isError($result)) {
            return ($result);
        }
        $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
                    BEGIN
                        DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
                    END ";
        $result = $this->query($query);
        //if (DB::isError($result)) {
            return ($result);
        //}
    }

    // }}}
    // {{{ sqliteRaiseError()

    /**
     * Get the file stats for the current database
     *
     * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
     * atime, mtime, ctime, blksize, blocks or a numeric key between
     * 0 and 12.
     *
     * @param string $arg the array key for stats()
     *
     * @return mixed  an array on an unspecified key, integer on a passed
     *                arg and false at a stats error
     */
    public function getDbFileStats($arg = '')
    {
        $stats = stat($this->dsn['database']);
        if ($stats == false) {
            return false;
        }
        if (is_array($stats)) {
            if (is_numeric($arg)) {
                if (((int)$arg <= 12) & ((int)$arg >= 0)) {
                    return false;
                }
                return $stats[$arg];
            }
            if (array_key_exists(trim($arg), $stats)) {
                return $stats[$arg];
            }
        }
        return $stats;
    }

    // }}}
    // {{{ errorNative()

    /**
     * Escapes a string according to the current DBMS's standards
     *
     * In SQLite, this makes things safe for inserts/updates, but may
     * cause problems when performing text comparisons against columns
     * containing binary data. See the
     * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
     *
     * @param string $str the string to be escaped
     *
     * @return string  the escaped string
     *
     * @since Method available since Release 1.6.1
     * @see DB_common::escapeSimple()
     */
    public function escapeSimple($str)
    {
        return @sqlite_escape_string($str);
    }

    // }}}
    // {{{ errorCode()

    /**
     * Adds LIMIT clauses to a query string according to current DBMS standards
     *
     * @param string $query the query to modify
     * @param int $from the row to start to fetching (0 = the first row)
     * @param int $count the numbers of rows to fetch
     * @param mixed $params array, string or numeric data to be used in
     *                         execution of the statement.  Quantity of items
     *                         passed must match quantity of placeholders in
     *                         query:  meaning 1 placeholder for non-array
     *                         parameters or 1 placeholder per array element.
     *
     * @return string  the query string with LIMIT clauses added
     *
     * @access protected
     */
    public function modifyLimitQuery($query, $from, $count, $params = array())
    {
        return "$query LIMIT $count OFFSET $from";
    }

    // }}}
    // {{{ tableInfo()

    /**
     * Returns information about a table
     *
     * @param string $result a string containing the name of a table
     * @param int $mode a valid tableInfo mode
     *
     * @return array|object
     *                 A DB_Error object on failure.
     *
     * @see DB_common::tableInfo()
     * @since Method available since Release 1.7.0
     */
    public function tableInfo($result, $mode = null)
    {
        if (is_string($result)) {
            /*
             * Probably received a table name.
             * Create a result resource identifier.
             */
            $id = @sqlite_array_query(
                $this->connection,
                "PRAGMA table_info('$result');",
                SQLITE_ASSOC
            );
            $got_string = true;
        } else {
            $this->last_query = '';
            return $this->raiseError(
                DB_ERROR_NOT_CAPABLE,
                null,
                null,
                null,
                'This DBMS can not obtain tableInfo' .
                ' from result sets'
            );
        }

        if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
            $case_func = 'strtolower';
        } else {
            $case_func = 'strval';
        }

        $count = count($id);
        $res = array();

        if ($mode) {
            $res['num_fields'] = $count;
        }

        for ($i = 0; $i < $count; $i++) {
            if (strpos($id[$i]['type'], '(') !== false) {
                $bits = explode('(', $id[$i]['type']);
                $type = $bits[0];
                $len = rtrim($bits[1], ')');
            } else {
                $type = $id[$i]['type'];
                $len = 0;
            }

            $flags = '';
            if ($id[$i]['pk']) {
                $flags .= 'primary_key ';
                if (strtoupper($type) == 'INTEGER') {
                    $flags .= 'auto_increment ';
                }
            }
            if ($id[$i]['notnull']) {
                $flags .= 'not_null ';
            }
            if ($id[$i]['dflt_value'] !== null) {
                $flags .= 'default_' . rawurlencode($id[$i]['dflt_value']);
            }
            $flags = trim($flags);

            $res[$i] = array(
                'table' => $case_func($result),
                'name' => $case_func($id[$i]['name']),
                'type' => $type,
                'len' => $len,
                'flags' => $flags,
            );

            if ($mode & DB_TABLEINFO_ORDER) {
                $res['order'][$res[$i]['name']] = $i;
            }
            if ($mode & DB_TABLEINFO_ORDERTABLE) {
                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
            }
        }

        return $res;
    }

    // }}}
    // {{{ getSpecialQuery()

    /**
     * Obtains the query string needed for listing a given type of objects
     *
     * @param string $type the kind of objects you want to retrieve
     * @param array $args SQLITE DRIVER ONLY: a private array of arguments
     *                       used by the getSpecialQuery().  Do not use
     *                       this directly.
     *
     * @return string  the SQL query string or null if the driver doesn't
     *                  support the object type requested
     *
     * @access protected
     * @see DB_common::getListOf()
     */
    public function getSpecialQuery($type, $args = array())
    {
        if (!is_array($args)) {
            return $this->raiseError(
                'no key specified',
                null,
                null,
                null,
                'Argument has to be an array.'
            );
        }

        switch ($type) {
            case 'master':
                return 'SELECT * FROM sqlite_master;';
            case 'tables':
                return "SELECT name FROM sqlite_master WHERE type='table' "
                    . 'UNION ALL SELECT name FROM sqlite_temp_master '
                    . "WHERE type='table' ORDER BY name;";
            case 'schema':
                return 'SELECT sql FROM (SELECT * FROM sqlite_master '
                    . 'UNION ALL SELECT * FROM sqlite_temp_master) '
                    . "WHERE type!='meta' "
                    . 'ORDER BY tbl_name, type DESC, name;';
            case 'schemax':
            case 'schema_x':
                /*
                 * Use like:
                 * $res = $db->query($db->getSpecialQuery('schema_x',
                 *                   array('table' => 'table3')));
                 */
                return 'SELECT sql FROM (SELECT * FROM sqlite_master '
                    . 'UNION ALL SELECT * FROM sqlite_temp_master) '
                    . "WHERE tbl_name LIKE '{$args['table']}' "
                    . "AND type!='meta' "
                    . 'ORDER BY type DESC, name;';
            case 'alter':
                /*
                 * SQLite does not support ALTER TABLE; this is a helper query
                 * to handle this. 'table' represents the table name, 'rows'
                 * the news rows to create, 'save' the row(s) to keep _with_
                 * the data.
                 *
                 * Use like:
                 * $args = array(
                 *     'table' => $table,
                 *     'rows'  => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
                 *     'save'  => "NULL, titel, content, datetime"
                 * );
                 * $res = $db->query( $db->getSpecialQuery('alter', $args));
                 */
                $rows = strtr($args['rows'], $this->keywords);

                $q = array(
                    'BEGIN TRANSACTION',
                    "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})",
                    "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}",
                    "DROP TABLE {$args['table']}",
                    "CREATE TABLE {$args['table']} ({$args['rows']})",
                    "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup",
                    "DROP TABLE {$args['table']}_backup",
                    'COMMIT',
                );

                /*
                 * This is a dirty hack, since the above query will not get
                 * executed with a single query call so here the query method
                 * will be called directly and return a select instead.
                 */
                foreach ($q as $query) {
                    $this->query($query);
                }
                return "SELECT * FROM {$args['table']};";
            default:
                return null;
        }
    }

    // }}}
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */

repo_name: andremichelle/gnu

license: mit


code:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Provides an object interface to a table row
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Database
 * @package    DB
 * @author     Stig Bakken <stig@php.net>
 * @copyright  1997-2007 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    CVS: $Id$
 * @link       http://pear.php.net/package/DB
 */

/**
 * Obtain the DB class so it can be extended from
 */
require_once 'DB.php';

/**
 * Provides an object interface to a table row
 *
 * It lets you add, delete and change rows using objects rather than SQL
 * statements.
 *
 * @category   Database
 * @package    DB
 * @author     Stig Bakken <stig@php.net>
 * @copyright  1997-2007 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: 1.9.2
 * @link       http://pear.php.net/package/DB
 */
class DB_storage extends PEAR
{
    // {{{ properties

    /** the name of the table (or view, if the backend database supports
     * updates in views) we hold data from */
    public $_table = null;

    /** which column(s) in the table contains primary keys, can be a
     * string for single-column primary keys, or an array of strings
     * for multiple-column primary keys */
    public $_keycolumn = null;

    /** DB connection handle used for all transactions */
    public $_dbh = null;

    /** an assoc with the names of database fields stored as properties
     * in this object */
    public $_properties = array();

    /** an assoc with the names of the properties in this object that
     * have been changed since they were fetched from the database */
    public $_changes = array();

    /** flag that decides if data in this object can be changed.
     * objects that don't have their table's key column in their
     * property lists will be flagged as read-only. */
    public $_readonly = false;

    /** function or method that implements a validator for fields that
     * are set, this validator function returns true if the field is
     * valid, false if not */
    public $_validator = null;

    // }}}
    // {{{ constructor

    /**
     * Constructor
     *
     * @param $table string the name of the database table
     *
     * @param $keycolumn mixed string with name of key column, or array of
     * strings if the table has a primary key of more than one column
     *
     * @param $dbh object database connection object
     *
     * @param $validator mixed function or method used to validate
     * each new value, called with three parameters: the name of the
     * field/column that is changing, a reference to the new value and
     * a reference to this object
     *
     */
    public function __construct($table, $keycolumn, &$dbh, $validator = null)
    {
        $this->PEAR('DB_Error');
        $this->_table = $table;
        $this->_keycolumn = $keycolumn;
        $this->_dbh = $dbh;
        $this->_readonly = false;
        $this->_validator = $validator;
    }

    // }}}
    // {{{ _makeWhere()

    /**
     * Create a new (empty) row in the configured table for this
     * object.
     * @param $newpk
     * @return |null
     */
    public function insert($newpk)
    {
        if (is_array($this->_keycolumn)) {
            $primarykey = $this->_keycolumn;
        } else {
            $primarykey = array($this->_keycolumn);
        }
        settype($newpk, "array");
        for ($i = 0; $i < sizeof($primarykey); $i++) {
            $pkvals[] = $this->_dbh->quote($newpk[$i]);
        }

        $sth = $this->_dbh->query("INSERT INTO $this->_table (" .
            implode(",", $primarykey) . ") VALUES(" .
            implode(",", $pkvals) . ")");
        if (DB::isError($sth)) {
            return $sth;
        }
        if (sizeof($newpk) == 1) {
            $newpk = $newpk[0];
        }
        $this->setup($newpk);
        return null;
    }

    // }}}
    // {{{ setup()

    /**
     * Method used to initialize a DB_storage object from the
     * configured table.
     *
     * @param $keyval mixed the key[s] of the row to fetch (string or array)
     *
     * @return int|object
     */
    public function setup($keyval)
    {
        $whereclause = $this->_makeWhere($keyval);
        $query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause;
        $sth = $this->_dbh->query($query);
        if (DB::isError($sth)) {
            return $sth;
        }
        $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
        if (DB::isError($row)) {
            return $row;
        }
        if (!$row) {
            return $this->raiseError(
                null,
                DB_ERROR_NOT_FOUND,
                null,
                null,
                $query,
                null,
                true
            );
        }
        foreach ($row as $key => $value) {
            $this->_properties[$key] = true;
            $this->$key = $value;
        }
        return DB_OK;
    }

    // }}}
    // {{{ insert()

    /**
     * Utility method to build a "WHERE" clause to locate ourselves in
     * the table.
     *
     * XXX future improvement: use rowids?
     *
     * @access private
     * @param null $keyval
     * @return mixed|string|null
     */
    public function _makeWhere($keyval = null)
    {
        if (is_array($this->_keycolumn)) {
            if ($keyval === null) {
                for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
                    $keyval[] = $this->{$this->_keycolumn[$i]};
                }
            }
            $whereclause = '';
            for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
                if ($i > 0) {
                    $whereclause .= ' AND ';
                }
                $whereclause .= $this->_keycolumn[$i];
                if (is_null($keyval[$i])) {
                    // there's not much point in having a NULL key,
                    // but we support it anyway
                    $whereclause .= ' IS NULL';
                } else {
                    $whereclause .= ' = ' . $this->_dbh->quote($keyval[$i]);
                }
            }
        } else {
            if ($keyval === null) {
                $keyval = @$this->{$this->_keycolumn};
            }
            $whereclause = $this->_keycolumn;
            if (is_null($keyval)) {
                // there's not much point in having a NULL key,
                // but we support it anyway
                $whereclause .= ' IS NULL';
            } else {
                $whereclause .= ' = ' . $this->_dbh->quote($keyval);
            }
        }
        return $whereclause;
    }

    // }}}
    // {{{ toString()

    /**
     * Output a simple description of this DB_storage object.
     * @return string object description
     */
    public function toString()
    {
        $info = strtolower(get_class($this));
        $info .= " (table=";
        $info .= $this->_table;
        $info .= ", keycolumn=";
        if (is_array($this->_keycolumn)) {
            $info .= "(" . implode(",", $this->_keycolumn) . ")";
        } else {
            $info .= $this->_keycolumn;
        }
        $info .= ", dbh=";
        if (is_object($this->_dbh)) {
            $info .= $this->_dbh->toString();
        } else {
            $info .= "null";
        }
        $info .= ")";
        if (sizeof($this->_properties)) {
            $info .= " [loaded, key=";
            $keyname = $this->_keycolumn;
            if (is_array($keyname)) {
                $info .= "(";
                for ($i = 0; $i < sizeof($keyname); $i++) {
                    if ($i > 0) {
                        $info .= ",";
                    }
                    $info .= $this->$keyname[$i];
                }
                $info .= ")";
            } else {
                $info .= $this->$keyname;
            }
            $info .= "]";
        }
        if (sizeof($this->_changes)) {
            $info .= " [modified]";
        }
        return $info;
    }

    // }}}
    // {{{ dump()

    /**
     * Dump the contents of this object to "standard output".
     */
    public function dump()
    {
        foreach ($this->_properties as $prop => $foo) {
            print "$prop = ";
            print htmlentities($this->$prop);
            print "<br />\n";
        }
    }

    // }}}
    // {{{ &create()

    /**
     * Static method used to create new DB storage objects.
     * @param $table
     * @param $data assoc. array where the keys are the names
     *              of properties/columns
     * @return object a new instance of DB_storage or a subclass of it
     */
    public function &create($table, &$data)
    {
        $classname = strtolower(get_class($this));
        $obj = new $classname($table);
        foreach ($data as $name => $value) {
            $obj->_properties[$name] = true;
            $obj->$name = &$value;
        }
        return $obj;
    }

    // }}}
    // {{{ loadFromQuery()

    /**
     * Loads data into this object from the given query.  If this
     * object already contains table data, changes will be saved and
     * the object re-initialized first.
     *
     * @param $query SQL query
     *
     * @param $params parameter list in case you want to use
     * prepare/execute mode
     *
     * @return int DB_OK on success, DB_WARNING_READ_ONLY if the
     * returned object is read-only (because the object's specified
     * key column was not found among the columns returned by $query),
     * or another DB error code in case of errors.
     */
    // XXX commented out for now
    /*
        function loadFromQuery($query, $params = null)
        {
            if (sizeof($this->_properties)) {
                if (sizeof($this->_changes)) {
                    $this->store();
                    $this->_changes = array();
                }
                $this->_properties = array();
            }
            $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
            if (DB::isError($rowdata)) {
                return $rowdata;
            }
            reset($rowdata);
            $found_keycolumn = false;
            while (list($key, $value) = each($rowdata)) {
                if ($key == $this->_keycolumn) {
                    $found_keycolumn = true;
                }
                $this->_properties[$key] = true;
                $this->$key = &$value;
                unset($value); // have to unset, or all properties will
                               // refer to the same value
            }
            if (!$found_keycolumn) {
                $this->_readonly = true;
                return DB_WARNING_READ_ONLY;
            }
            return DB_OK;
        }
     */

    // }}}
    // {{{ set()

    /**
     * Modify an attriute value.
     * @param $property
     * @param $newvalue
     * @return bool|object
     */
    public function set($property, $newvalue)
    {
        // only change if $property is known and object is not
        // read-only
        if ($this->_readonly) {
            return $this->raiseError(
                null,
                DB_WARNING_READ_ONLY,
                null,
                null,
                null,
                null,
                true
            );
        }
        if (@isset($this->_properties[$property])) {
            if (empty($this->_validator)) {
                $valid = true;
            } else {
                $valid = @call_user_func(
                    $this->_validator,
                    $this->_table,
                    $property,
                    $newvalue,
                    $this->$property,
                    $this
                );
            }
            if ($valid) {
                $this->$property = $newvalue;
                if (empty($this->_changes[$property])) {
                    $this->_changes[$property] = 0;
                } else {
                    $this->_changes[$property]++;
                }
            } else {
                return $this->raiseError(
                    null,
                    DB_ERROR_INVALID,
                    null,
                    null,
                    "invalid field: $property",
                    null,
                    true
                );
            }
            return true;
        }
        return $this->raiseError(
            null,
            DB_ERROR_NOSUCHFIELD,
            null,
            null,
            "unknown field: $property",
            null,
            true
        );
    }

    // }}}
    // {{{ &get()

    /**
     * Fetch an attribute value.
     *
     * @param string attribute name
     *
     * @return attribute contents, or null if the attribute name is
     * unknown
     */
    public function &get($property)
    {
        // only return if $property is known
        if (isset($this->_properties[$property])) {
            return $this->$property;
        }
        $tmp = null;
        return $tmp;
    }

    // }}}
    // {{{ _DB_storage()

    /**
     * Destructor, calls DB_storage::store() if there are changes
     * that are to be kept.
     */
    public function _DB_storage()
    {
        if (sizeof($this->_changes)) {
            $this->store();
        }
        $this->_properties = array();
        $this->_changes = array();
        $this->_table = null;
    }

    // }}}
    // {{{ store()

    /**
     * Stores changes to this object in the database.
     *
     * @return DB_OK|int
     */
    public function store()
    {
        $params = array();
        $vars = array();
        foreach ($this->_changes as $name => $foo) {
            $params[] = &$this->$name;
            $vars[] = $name . ' = ?';
        }
        if ($vars) {
            $query = 'UPDATE ' . $this->_table . ' SET ' .
                implode(', ', $vars) . ' WHERE ' .
                $this->_makeWhere();
            $stmt = $this->_dbh->prepare($query);
            $res = $this->_dbh->execute($stmt, $params);
            if (DB::isError($res)) {
                return $res;
            }
            $this->_changes = array();
        }
        return DB_OK;
    }

    // }}}
    // {{{ remove()

    /**
     * Remove the row represented by this object from the database.
     *
     * @return mixed DB_OK or a DB error
     */
    public function remove()
    {
        if ($this->_readonly) {
            return $this->raiseError(
                null,
                DB_WARNING_READ_ONLY,
                null,
                null,
                null,
                null,
                true
            );
        }
        $query = 'DELETE FROM ' . $this->_table . ' WHERE ' .
            $this->_makeWhere();
        $res = $this->_dbh->query($query);
        if (DB::isError($res)) {
            return $res;
        }
        foreach ($this->_properties as $prop => $foo) {
            unset($this->$prop);
        }
        $this->_properties = array();
        $this->_changes = array();
        return DB_OK;
    }

    // }}}
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */