From 63d6e6dfc35e6d82c4a64f37c408794c163becd4 Mon Sep 17 00:00:00 2001
From: thomascube <thomas@roundcube.net>
Date: Wed, 28 Sep 2011 15:16:41 -0400
Subject: [PATCH] Bump versions to 0.6 stable

---
 program/lib/MDB2/Driver/sqlite.php |  648 ++++++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 468 insertions(+), 180 deletions(-)

diff --git a/program/lib/MDB2/Driver/sqlite.php b/program/lib/MDB2/Driver/sqlite.php
old mode 100755
new mode 100644
index 231b429..e1726b0
--- a/program/lib/MDB2/Driver/sqlite.php
+++ b/program/lib/MDB2/Driver/sqlite.php
@@ -3,7 +3,7 @@
 // +----------------------------------------------------------------------+
 // | PHP versions 4 and 5                                                 |
 // +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
+// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,                 |
 // | Stig. S. Bakken, Lukas Smith                                         |
 // | All rights reserved.                                                 |
 // +----------------------------------------------------------------------+
@@ -40,10 +40,10 @@
 // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
 // | POSSIBILITY OF SUCH DAMAGE.                                          |
 // +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@backendmedia.com>                         |
+// | Author: Lukas Smith <smith@pooteeweet.org>                           |
 // +----------------------------------------------------------------------+
 //
-// $Id$
+// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $
 //
 
 /**
@@ -51,21 +51,25 @@
  *
  * @package MDB2
  * @category Database
- * @author  Lukas Smith <smith@backendmedia.com>
+ * @author  Lukas Smith <smith@pooteeweet.org>
  */
 class MDB2_Driver_sqlite extends MDB2_Driver_Common
 {
     // {{{ properties
-    var $escape_quotes = "'";
+    var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
+
+    var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
 
     var $_lasterror = '';
+
+    var $fix_assoc_fields_names = false;
 
     // }}}
     // {{{ constructor
 
     /**
-    * Constructor
-    */
+     * Constructor
+     */
     function __construct()
     {
         parent::__construct();
@@ -73,23 +77,35 @@
         $this->phptype = 'sqlite';
         $this->dbsyntax = 'sqlite';
 
-        $this->supported['sequences'] = true;
+        $this->supported['sequences'] = 'emulated';
         $this->supported['indexes'] = true;
         $this->supported['affected_rows'] = true;
         $this->supported['summary_functions'] = true;
         $this->supported['order_by_text'] = true;
-        $this->supported['current_id'] = true;
+        $this->supported['current_id'] = 'emulated';
         $this->supported['limit_queries'] = true;
         $this->supported['LOBs'] = true;
         $this->supported['replace'] = true;
         $this->supported['transactions'] = true;
+        $this->supported['savepoints'] = false;
         $this->supported['sub_selects'] = true;
+        $this->supported['triggers'] = true;
         $this->supported['auto_increment'] = true;
+        $this->supported['primary_key'] = false; // requires alter table implementation
+        $this->supported['result_introspection'] = false; // not implemented
+        $this->supported['prepared_statements'] = 'emulated';
+        $this->supported['identifier_quoting'] = true;
+        $this->supported['pattern_escaping'] = false;
+        $this->supported['new_link'] = false;
 
+        $this->options['DBA_username'] = false;
+        $this->options['DBA_password'] = false;
         $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
         $this->options['fixed_float'] = 0;
         $this->options['database_path'] = '';
         $this->options['database_extension'] = '';
+        $this->options['server_version'] = '';
+        $this->options['max_identifiers_length'] = 128; //no real limit
     }
 
     // }}}
@@ -108,9 +124,14 @@
         if ($this->connection) {
             $native_code = @sqlite_last_error($this->connection);
         }
-        $native_msg  = @sqlite_error_string($native_code);
+        $native_msg = $this->_lasterror
+            ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
+            
+        // PHP 5.2+ prepends the function name to $php_errormsg, so we need
+        // this hack to work around it, per bug #9599.
+        $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
 
-        if (is_null($error)) {
+        if (null === $error) {
             static $error_regexps;
             if (empty($error_regexps)) {
                 $error_regexps = array(
@@ -123,13 +144,14 @@
                     '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
                     '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
                     '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
+                    '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
                     '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
                     '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
                     '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
                  );
             }
             foreach ($error_regexps as $regexp => $code) {
-                if (preg_match($regexp, $this->_lasterror)) {
+                if (preg_match($regexp, $native_msg)) {
                     $error = $code;
                     break;
                 }
@@ -145,27 +167,37 @@
      * Quotes a string so it can be safely used in a query. It will quote
      * the text so it can safely be used within a query.
      *
-     * @param string $text the input string to quote
-     * @return string quoted string
-     * @access public
+     * @param   string  the input string to quote
+     * @param   bool    escape wildcards
+     *
+     * @return  string  quoted string
+     *
+     * @access  public
      */
-    function escape($text)
+    function escape($text, $escape_wildcards = false)
     {
-        return @sqlite_escape_string($text);
+        $text = @sqlite_escape_string($text);
+        return $text;
     }
 
     // }}}
     // {{{ beginTransaction()
 
     /**
-     * Start a transaction.
+     * Start a transaction or set a savepoint.
      *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
+     * @param   string  name of a savepoint to set
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
+     *
+     * @access  public
      */
-    function beginTransaction()
+    function beginTransaction($savepoint = null)
     {
-        $this->debug('starting transaction', 'beginTransaction');
+        $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
+        if (null !== $savepoint) {
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+                'savepoints are not supported', __FUNCTION__);
+        }
         if ($this->in_transaction) {
             return MDB2_OK;  //nothing to do
         }
@@ -187,18 +219,27 @@
 
     /**
      * Commit the database changes done during a transaction that is in
-     * progress.
+     * progress or release a savepoint. This function may only be called when
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new
+     * transaction is implicitly started after committing the pending changes.
      *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
+     * @param   string  name of a savepoint to release
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
+     *
+     * @access  public
      */
-    function commit()
+    function commit($savepoint = null)
     {
-        $this->debug('commit transaction', 'commit');
+        $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
         if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR, null, null,
-                'commit: transaction changes are being auto committed');
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+                'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
         }
+        if (null !== $savepoint) {
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+                'savepoints are not supported', __FUNCTION__);
+        }
+
         $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
         $result = $this->_doQuery($query, true);
         if (PEAR::isError($result)) {
@@ -209,22 +250,31 @@
     }
 
     // }}}
-    // {{{ rollback()
+    // {{{
 
     /**
-     * Cancel any database changes done during a transaction that is in
-     * progress.
+     * Cancel any database changes done during a transaction or since a specific
+     * savepoint that is in progress. This function may only be called when
+     * auto-committing is disabled, otherwise it will fail. Therefore, a new
+     * transaction is implicitly started after canceling the pending changes.
      *
-     * @return mixed MDB2_OK on success, a MDB2 error on failure
-     * @access public
+     * @param   string  name of a savepoint to rollback to
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
+     *
+     * @access  public
      */
-    function rollback()
+    function rollback($savepoint = null)
     {
-        $this->debug('rolling back transaction', 'rollback');
+        $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
         if (!$this->in_transaction) {
-            return $this->raiseError(MDB2_ERROR, null, null,
-                'rollback: transactions can not be rolled back when changes are auto committed');
+            return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+                'rollback cannot be done changes are auto committed', __FUNCTION__);
         }
+        if (null !== $savepoint) {
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+                'savepoints are not supported', __FUNCTION__);
+        }
+
         $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
         $result = $this->_doQuery($query, true);
         if (PEAR::isError($result)) {
@@ -232,6 +282,47 @@
         }
         $this->in_transaction = false;
         return MDB2_OK;
+    }
+
+    // }}}
+    // {{{ function setTransactionIsolation()
+
+    /**
+     * Set the transacton isolation level.
+     *
+     * @param   string  standard isolation level
+     *                  READ UNCOMMITTED (allows dirty reads)
+     *                  READ COMMITTED (prevents dirty reads)
+     *                  REPEATABLE READ (prevents nonrepeatable reads)
+     *                  SERIALIZABLE (prevents phantom reads)
+     * @param   array some transaction options:
+     *                  'wait' => 'WAIT' | 'NO WAIT'
+     *                  'rw'   => 'READ WRITE' | 'READ ONLY'
+     *
+     * @return  mixed   MDB2_OK on success, a MDB2 error on failure
+     *
+     * @access  public
+     * @since   2.1.1
+     */
+    function setTransactionIsolation($isolation, $options = array())
+    {
+        $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
+        switch ($isolation) {
+        case 'READ UNCOMMITTED':
+            $isolation = 0;
+            break;
+        case 'READ COMMITTED':
+        case 'REPEATABLE READ':
+        case 'SERIALIZABLE':
+            $isolation = 1;
+            break;
+        default:
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+                'isolation level is not supported: '.$isolation, __FUNCTION__);
+        }
+
+        $query = "PRAGMA read_uncommitted=$isolation";
+        return $this->_doQuery($query, true);
     }
 
     // }}}
@@ -245,7 +336,7 @@
      */
     function _getDatabaseFile($database_name)
     {
-        if ($database_name == '') {
+        if ($database_name === '' || $database_name === ':memory:') {
             return $database_name;
         }
         return $this->options['database_path'].$database_name.$this->options['database_extension'];
@@ -263,7 +354,8 @@
     {
         $database_file = $this->_getDatabaseFile($this->database_name);
         if (is_resource($this->connection)) {
-            if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
+            //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
+            if (MDB2::areEquals($this->connected_dsn, $this->dsn)
                 && $this->connected_database_name == $database_file
                 && $this->opened_persistent == $this->options['persistent']
             ) {
@@ -274,13 +366,19 @@
 
         if (!PEAR::loadExtension($this->phptype)) {
             return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
-                'connect: extension '.$this->phptype.' is not compiled into PHP');
+                'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
         }
 
-        if (!empty($this->database_name)) {
+        if (empty($this->database_name)) {
+            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+            'unable to establish a connection', __FUNCTION__);
+        }
+
+        if ($database_file !== ':memory:') {
             if (!file_exists($database_file)) {
                 if (!touch($database_file)) {
-                    return $this->raiseError(MDB2_ERROR_NOT_FOUND);
+                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+                        'Could not create database file', __FUNCTION__);
                 }
                 if (!isset($this->dsn['mode'])
                     || !is_numeric($this->dsn['mode'])
@@ -290,35 +388,71 @@
                     $mode = octdec($this->dsn['mode']);
                 }
                 if (!chmod($database_file, $mode)) {
-                    return $this->raiseError(MDB2_ERROR_NOT_FOUND);
+                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+                        'Could not be chmodded database file', __FUNCTION__);
                 }
                 if (!file_exists($database_file)) {
-                    return $this->raiseError(MDB2_ERROR_NOT_FOUND);
+                    return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
+                        'Could not be found database file', __FUNCTION__);
                 }
             }
             if (!is_file($database_file)) {
-                return $this->raiseError(MDB2_ERROR_INVALID);
+                return $this->raiseError(MDB2_ERROR_INVALID, null, null,
+                        'Database is a directory name', __FUNCTION__);
             }
             if (!is_readable($database_file)) {
-                return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION);
+                return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
+                        'Could not read database file', __FUNCTION__);
             }
+        }
 
-            $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
-            $php_errormsg = '';
+        $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
+        $php_errormsg = '';
+        if (version_compare('5.1.0', PHP_VERSION, '>')) {
             @ini_set('track_errors', true);
             $connection = @$connect_function($database_file);
             @ini_restore('track_errors');
-            $this->_lasterror = isset($php_errormsg) ? $php_errormsg : '';
-            if (!$connection) {
-                return $this->raiseError(MDB2_ERROR_CONNECT_FAILED);
-            }
-            $this->connection = $connection;
-            $this->connected_dsn = $this->dsn;
-            $this->connected_database_name = $database_file;
-            $this->opened_persistent = $this->getoption('persistent');
-            $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
+        } else {
+            $connection = @$connect_function($database_file, 0666, $php_errormsg);
         }
+        $this->_lasterror = $php_errormsg;
+        if (!$connection) {
+            return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
+            'unable to establish a connection', __FUNCTION__);
+        }
+
+        if ($this->fix_assoc_fields_names ||
+            $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
+        {
+            @sqlite_query("PRAGMA short_column_names = 1", $connection);
+            $this->fix_assoc_fields_names = true;
+        }
+
+        $this->connection = $connection;
+        $this->connected_dsn = $this->dsn;
+        $this->connected_database_name = $database_file;
+        $this->opened_persistent = $this->getoption('persistent');
+        $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
+
         return MDB2_OK;
+    }
+
+    // }}}
+    // {{{ databaseExists()
+
+    /**
+     * check if given database name is exists?
+     *
+     * @param string $name    name of the database that should be checked
+     *
+     * @return mixed true/false on success, a MDB2 error on failure
+     * @access public
+     */
+    function databaseExists($name)
+    {
+        $database_file = $this->_getDatabaseFile($name);
+        $result = file_exists($database_file);
+        return $result;
     }
 
     // }}}
@@ -327,6 +461,8 @@
     /**
      * Log out and disconnect from the database.
      *
+     * @param  boolean $force if the disconnect should be forced even if the
+     *                        connection is opened persistently
      * @return mixed true on success, false if not connected and error
      *                object on error
      * @access public
@@ -334,12 +470,26 @@
     function disconnect($force = true)
     {
         if (is_resource($this->connection)) {
+            if ($this->in_transaction) {
+                $dsn = $this->dsn;
+                $database_name = $this->database_name;
+                $persistent = $this->options['persistent'];
+                $this->dsn = $this->connected_dsn;
+                $this->database_name = $this->connected_database_name;
+                $this->options['persistent'] = $this->opened_persistent;
+                $this->rollback();
+                $this->dsn = $dsn;
+                $this->database_name = $database_name;
+                $this->options['persistent'] = $persistent;
+            }
+
             if (!$this->opened_persistent || $force) {
                 @sqlite_close($this->connection);
             }
-            $this->connection = 0;
+        } else {
+            return false;
         }
-        return MDB2_OK;
+        return parent::disconnect($force);
     }
 
     // }}}
@@ -348,47 +498,84 @@
     /**
      * Execute a query
      * @param string $query  query
-     * @param boolean $isManip  if the query is a manipulation query
+     * @param boolean $is_manip  if the query is a manipulation query
      * @param resource $connection
      * @param string $database_name
      * @return result or error object
      * @access protected
      */
-    function _doQuery($query, $isManip = false, $connection = null, $database_name = null)
+    function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
     {
         $this->last_query = $query;
-        $this->debug($query, 'query');
-        if ($this->options['disable_query']) {
-            if ($isManip) {
-                return MDB2_OK;
+        $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
+        if ($result) {
+            if (PEAR::isError($result)) {
+                return $result;
             }
-            return null;
+            $query = $result;
+        }
+        if ($this->options['disable_query']) {
+            $result = $is_manip ? 0 : null;
+            return $result;
         }
 
-        if (is_null($connection)) {
-            $error = $this->connect();
-            if (PEAR::isError($error)) {
-                return $error;
+        if (null === $connection) {
+            $connection = $this->getConnection();
+            if (PEAR::isError($connection)) {
+                return $connection;
             }
-            $connection = $this->connection;
         }
 
         $function = $this->options['result_buffering']
             ? 'sqlite_query' : 'sqlite_unbuffered_query';
         $php_errormsg = '';
-        ini_set('track_errors', true);
-        $result = @$function($query.';', $connection);
-        ini_restore('track_errors');
-        $this->_lasterror = isset($php_errormsg) ? $php_errormsg : '';
+        if (version_compare('5.1.0', PHP_VERSION, '>')) {
+            @ini_set('track_errors', true);
+            do {
+                $result = @$function($query.';', $connection);
+            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
+            @ini_restore('track_errors');
+        } else {
+            do {
+                $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
+            } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
+        }
+        $this->_lasterror = $php_errormsg;
 
         if (!$result) {
-            return $this->raiseError();
+            $code = null;
+            if (0 === strpos($this->_lasterror, 'no such table')) {
+                $code = MDB2_ERROR_NOSUCHTABLE;
+            }
+            $err = $this->raiseError($code, null, null,
+                'Could not execute statement', __FUNCTION__);
+            return $err;
         }
 
-        if ($isManip) {
-            return @sqlite_changes($connection);
-        }
+        $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
         return $result;
+    }
+
+    // }}}
+    // {{{ _affectedRows()
+
+    /**
+     * Returns the number of rows affected
+     *
+     * @param resource $result
+     * @param resource $connection
+     * @return mixed MDB2 Error Object or the number of rows affected
+     * @access private
+     */
+    function _affectedRows($connection, $result = null)
+    {
+        if (null === $connection) {
+            $connection = $this->getConnection();
+            if (PEAR::isError($connection)) {
+                return $connection;
+            }
+        }
+        return @sqlite_changes($connection);
     }
 
     // }}}
@@ -398,10 +585,13 @@
      * Changes a query string for various DBMS specific reasons
      *
      * @param string $query  query to modify
-     * @return the new (modified) query
+     * @param boolean $is_manip  if it is a DML query
+     * @param integer $limit  limit the number of rows
+     * @param integer $offset  start reading from given offset
+     * @return string modified query
      * @access protected
      */
-    function _modifyQuery($query, $isManip, $limit, $offset)
+    function _modifyQuery($query, $is_manip, $limit, $offset)
     {
         if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
@@ -410,21 +600,59 @@
             }
         }
         if ($limit > 0
-            && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i', $query)
+            && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
         ) {
             $query = rtrim($query);
             if (substr($query, -1) == ';') {
                 $query = substr($query, 0, -1);
             }
-            if ($isManip) {
-                $query .= " LIMIT $limit";
+            if ($is_manip) {
+                $query.= " LIMIT $limit";
             } else {
-                $query .= " LIMIT $offset,$limit";
+                $query.= " LIMIT $offset,$limit";
             }
         }
         return $query;
     }
 
+    // }}}
+    // {{{ getServerVersion()
+
+    /**
+     * return version information about the server
+     *
+     * @param bool   $native  determines if the raw version string should be returned
+     * @return mixed array/string with version information or MDB2 error object
+     * @access public
+     */
+    function getServerVersion($native = false)
+    {
+        $server_info = false;
+        if ($this->connected_server_info) {
+            $server_info = $this->connected_server_info;
+        } elseif ($this->options['server_version']) {
+            $server_info = $this->options['server_version'];
+        } elseif (function_exists('sqlite_libversion')) {
+            $server_info = @sqlite_libversion();
+        }
+        if (!$server_info) {
+            return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
+                'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
+        }
+        // cache server_info
+        $this->connected_server_info = $server_info;
+        if (!$native) {
+            $tmp = explode('.', $server_info, 3);
+            $server_info = array(
+                'major' => isset($tmp[0]) ? $tmp[0] : null,
+                'minor' => isset($tmp[1]) ? $tmp[1] : null,
+                'patch' => isset($tmp[2]) ? $tmp[2] : null,
+                'extra' => null,
+                'native' => $server_info,
+            );
+        }
+        return $server_info;
+    }
 
     // }}}
     // {{{ replace()
@@ -432,8 +660,7 @@
     /**
      * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
      * query, except that if there is already a row in the table with the same
-     * key field values, the REPLACE query just updates its values instead of
-     * inserting a new row.
+     * key field values, the old row is deleted before the new row is inserted.
      *
      * The REPLACE type of query does not make part of the SQL standards. Since
      * practically only SQLite implements it natively, this type of query is
@@ -502,41 +729,54 @@
             $name = key($fields);
             if ($colnum > 0) {
                 $query .= ',';
-                $values .= ',';
+                $values.= ',';
             }
-            $query .= $name;
+            $query.= $this->quoteIdentifier($name, true);
             if (isset($fields[$name]['null']) && $fields[$name]['null']) {
                 $value = 'NULL';
             } else {
-                $value = $this->quote($fields[$name]['value'], $fields[$name]['type']);
+                $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
+                $value = $this->quote($fields[$name]['value'], $type);
+                if (PEAR::isError($value)) {
+                    return $value;
+                }
             }
-            $values .= $value;
+            $values.= $value;
             if (isset($fields[$name]['key']) && $fields[$name]['key']) {
                 if ($value === 'NULL') {
                     return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                        'replace: key value '.$name.' may not be NULL');
+                        'key value '.$name.' may not be NULL', __FUNCTION__);
                 }
                 $keys++;
             }
         }
         if ($keys == 0) {
             return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
-                'replace: not specified which fields are keys');
+                'not specified which fields are keys', __FUNCTION__);
         }
+
+        $connection = $this->getConnection();
+        if (PEAR::isError($connection)) {
+            return $connection;
+        }
+
+        $table = $this->quoteIdentifier($table, true);
         $query = "REPLACE INTO $table ($query) VALUES ($values)";
-        $this->last_query = $query;
-        $this->debug($query, 'query');
-        return $this->_doQuery($query, true);
+        $result = $this->_doQuery($query, true, $connection);
+        if (PEAR::isError($result)) {
+            return $result;
+        }
+        return $this->_affectedRows($connection, $result);
     }
 
     // }}}
     // {{{ nextID()
 
     /**
-     * returns the next free id of a sequence
+     * Returns the next free id of a sequence
      *
-     * @param string  $seq_name name of the sequence
-     * @param boolean $ondemand when true the seqence is
+     * @param string $seq_name name of the sequence
+     * @param boolean $ondemand when true the sequence is
      *                          automatic created, if it
      *                          not exists
      *
@@ -545,71 +785,90 @@
      */
     function nextID($seq_name, $ondemand = true)
     {
-        $sequence_name = $this->getSequenceName($seq_name);
-        $query = "INSERT INTO $sequence_name (".$this->options['seqcol_name'].") VALUES (NULL)";
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+        $seqcol_name = $this->options['seqcol_name'];
+        $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
+        $this->pushErrorHandling(PEAR_ERROR_RETURN);
         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
         $result = $this->_doQuery($query, true);
         $this->popExpect();
+        $this->popErrorHandling();
         if (PEAR::isError($result)) {
             if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
-                $this->loadModule('Manager');
-                // Since we are creating the sequence on demand
-                // we know the first id = 1 so initialize the
-                // sequence at 2
-                $result = $this->manager->createSequence($seq_name, 2);
+                $this->loadModule('Manager', null, true);
+                $result = $this->manager->createSequence($seq_name);
                 if (PEAR::isError($result)) {
-                    return $this->raiseError(MDB2_ERROR, null, null,
-                        'nextID: on demand sequence '.$seq_name.' could not be created');
+                    return $this->raiseError($result, null, null,
+                        'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
                 } else {
-                    // First ID of a newly created sequence is 1
-                    return 1;
+                    return $this->nextID($seq_name, false);
                 }
             }
             return $result;
         }
-        $value = @sqlite_last_insert_rowid($this->connection);
-        if (is_numeric($value)
-            && PEAR::isError($this->_doQuery("DELETE FROM $sequence_name WHERE ".$this->options['seqcol_name']." < $value", true))
-        ) {
-            $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
+        $value = $this->lastInsertID();
+        if (is_numeric($value)) {
+            $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
+            $result = $this->_doQuery($query, true);
+            if (PEAR::isError($result)) {
+                $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
+            }
         }
         return $value;
     }
 
     // }}}
-    // {{{ getAfterID()
+    // {{{ lastInsertID()
 
     /**
-     * returns the autoincrement ID if supported or $id
+     * Returns the autoincrement ID if supported or $id or fetches the current
+     * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
      *
-     * @param mixed $id value as returned by getBeforeId()
      * @param string $table name of the table into which a new row was inserted
+     * @param string $field name of the field into which a new row was inserted
      * @return mixed MDB2 Error Object or id
      * @access public
      */
-    function getAfterID($id, $table)
+    function lastInsertID($table = null, $field = null)
     {
-        $this->loadModule('Native');
-        return $this->native->getInsertID();
+        $connection = $this->getConnection();
+        if (PEAR::isError($connection)) {
+            return $connection;
+        }
+        $value = @sqlite_last_insert_rowid($connection);
+        if (!$value) {
+            return $this->raiseError(null, null, null,
+                'Could not get last insert ID', __FUNCTION__);
+        }
+        return $value;
     }
 
     // }}}
     // {{{ currID()
 
     /**
-     * returns the current id of a sequence
+     * Returns the current id of a sequence
      *
-     * @param string  $seq_name name of the sequence
+     * @param string $seq_name name of the sequence
      * @return mixed MDB2 Error Object or id
      * @access public
      */
     function currID($seq_name)
     {
-        $sequence_name = $this->getSequenceName($seq_name);
-        return $this->queryOne("SELECT MAX(".$this->options['seqcol_name'].") FROM $sequence_name", 'integer');
+        $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
+        $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
+        $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
+        return $this->queryOne($query, 'integer');
     }
 }
 
+/**
+ * MDB2 SQLite result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author  Lukas Smith <smith@pooteeweet.org>
+ */
 class MDB2_Result_sqlite extends MDB2_Result_Common
 {
     // }}}
@@ -623,9 +882,9 @@
      * @return int data array on success, a MDB2 error on failure
      * @access public
      */
-    function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
+    function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
     {
-        if (!is_null($rownum)) {
+        if (null !== $rownum) {
             $seek = $this->seek($rownum);
             if (PEAR::isError($seek)) {
                 return $seek;
@@ -637,35 +896,46 @@
         if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
             $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
             if (is_array($row)
-                && $this->db->options['portability'] & MDB2_PORTABILITY_LOWERCASE
+                && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
             ) {
-                $row = array_change_key_case($row, CASE_LOWER);
+                $row = array_change_key_case($row, $this->db->options['field_case']);
             }
         } else {
            $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
         }
         if (!$row) {
-            if (is_null($this->result)) {
-                return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'fetchRow: resultset has already been freed');
+            if (false === $this->result) {
+                $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
+                    'resultset has already been freed', __FUNCTION__);
+                return $err;
             }
             return null;
         }
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL) {
-            $this->db->_convertEmptyArrayValuesToNull($row);
+        $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
+        $rtrim = false;
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
+            if (empty($this->types)) {
+                $mode += MDB2_PORTABILITY_RTRIM;
+            } else {
+                $rtrim = true;
+            }
         }
-        if (isset($this->values)) {
+        if ($mode) {
+            $this->db->_fixResultArrayValues($row, $mode);
+        }
+        if (!empty($this->types)) {
+            $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
+        }
+        if (!empty($this->values)) {
             $this->_assignBindColumns($row);
-        }
-        if (isset($this->types)) {
-            $row = $this->db->datatype->convertResultRow($this->types, $row);
         }
         if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
             $object_class = $this->db->options['fetch_class'];
             if ($object_class == 'stdClass') {
                 $row = (object) $row;
             } else {
-                $row = &new $object_class($row);
+                $rowObj = new $object_class($row);
+                $row = $rowObj;
             }
         }
         ++$this->rownum;
@@ -678,16 +948,10 @@
     /**
      * Retrieve the names of columns returned by the DBMS in a query result.
      *
-     * @return mixed                an associative array variable
-     *                              that will hold the names of columns. The
-     *                              indexes of the array are the column names
-     *                              mapped to lower case and the values are the
-     *                              respective numbers of the columns starting
-     *                              from 0. Some DBMS may not return any
-     *                              columns when the result set does not
-     *                              contain any rows.
-     *
-     *                              a MDB2 error on failure
+     * @return  mixed   Array variable that holds the names of columns as keys
+     *                  or an MDB2 error on failure.
+     *                  Some DBMS may not return any columns when the result set
+     *                  does not contain any rows.
      * @access private
      */
     function _getColumnNames()
@@ -701,8 +965,8 @@
             $column_name = @sqlite_field_name($this->result, $column);
             $columns[$column_name] = $column;
         }
-        if ($this->db->options['portability'] & MDB2_PORTABILITY_LOWERCASE) {
-            $columns = array_change_key_case($columns, CASE_LOWER);
+        if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
+            $columns = array_change_key_case($columns, $this->db->options['field_case']);
         }
         return $columns;
     }
@@ -720,37 +984,51 @@
     function numCols()
     {
         $cols = @sqlite_num_fields($this->result);
-        if (is_null($cols)) {
-            if (is_null($this->result)) {
+        if (null === $cols) {
+            if (false === $this->result) {
                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'numCols: resultset has already been freed');
+                    'resultset has already been freed', __FUNCTION__);
             }
-            return $this->db->raiseError();
+            if (null === $this->result) {
+                return count($this->types);
+            }
+            return $this->db->raiseError(null, null, null,
+                'Could not get column count', __FUNCTION__);
         }
         return $cols;
     }
 }
 
+/**
+ * MDB2 SQLite buffered result driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author  Lukas Smith <smith@pooteeweet.org>
+ */
 class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
 {
     // {{{ seek()
 
     /**
-    * seek to a specific row in a result set
-    *
-    * @param int    $rownum    number of the row where the data can be found
-    * @return mixed MDB2_OK on success, a MDB2 error on failure
-    * @access public
-    */
+     * Seek to a specific row in a result set
+     *
+     * @param int    $rownum    number of the row where the data can be found
+     * @return mixed MDB2_OK on success, a MDB2 error on failure
+     * @access public
+     */
     function seek($rownum = 0)
     {
         if (!@sqlite_seek($this->result, $rownum)) {
-            if (is_null($this->result)) {
+            if (false === $this->result) {
                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'seek: resultset has already been freed');
+                    'resultset has already been freed', __FUNCTION__);
+            }
+            if (null === $this->result) {
+                return MDB2_OK;
             }
             return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
-                'seek: tried to seek to an invalid row number ('.$rownum.')');
+                'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
         }
         $this->rownum = $rownum - 1;
         return MDB2_OK;
@@ -760,11 +1038,11 @@
     // {{{ valid()
 
     /**
-    * check if the end of the result set has been reached
-    *
-    * @return mixed true or false on sucess, a MDB2 error on failure
-    * @access public
-    */
+     * Check if the end of the result set has been reached
+     *
+     * @return mixed true or false on sucess, a MDB2 error on failure
+     * @access public
+     */
     function valid()
     {
         $numrows = $this->numRows();
@@ -778,28 +1056,38 @@
     // {{{ numRows()
 
     /**
-    * returns the number of rows in a result object
-    *
-    * @return mixed MDB2 Error Object or the number of rows
-    * @access public
-    */
+     * Returns the number of rows in a result object
+     *
+     * @return mixed MDB2 Error Object or the number of rows
+     * @access public
+     */
     function numRows()
     {
         $rows = @sqlite_num_rows($this->result);
-        if (is_null($rows)) {
-            if (is_null($this->result)) {
+        if (null === $rows) {
+            if (false === $this->result) {
                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
-                    'numRows: resultset has already been freed');
+                    'resultset has already been freed', __FUNCTION__);
             }
-            return $this->raiseError();
+            if (null === $this->result) {
+                return 0;
+            }
+            return $this->db->raiseError(null, null, null,
+                'Could not get row count', __FUNCTION__);
         }
         return $rows;
     }
 }
 
+/**
+ * MDB2 SQLite statement driver
+ *
+ * @package MDB2
+ * @category Database
+ * @author  Lukas Smith <smith@pooteeweet.org>
+ */
 class MDB2_Statement_sqlite extends MDB2_Statement_Common
 {
 
 }
-
 ?>
\ No newline at end of file

--
Gitblit v1.9.1