From 1671948dd0101fd0ac5f3e41fd3e5a8c1008a9cc Mon Sep 17 00:00:00 2001
From: sun <sun@unleashedmind.com>
Date: Tue, 5 Aug 2014 17:25:20 +0200
Subject: [PATCH 1/6] Issue #2318191 by sun: Fixed SQLite: StatementPrefetch
 is dead code due to logic error.

---
 .../Core/Database/Driver/sqlite/Connection.php     |  74 ++-
 .../Core/Database/Driver/sqlite/Statement.php      | 146 ------
 .../lib/Drupal/Core/Database/StatementPrefetch.php | 512 ---------------------
 3 files changed, 64 insertions(+), 668 deletions(-)
 delete mode 100644 core/lib/Drupal/Core/Database/Driver/sqlite/Statement.php
 delete mode 100644 core/lib/Drupal/Core/Database/StatementPrefetch.php

diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
index 6cacf4e..4e9807c 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
@@ -68,9 +68,6 @@ class Connection extends DatabaseConnection {
   public function __construct(\PDO $connection, array $connection_options) {
     parent::__construct($connection, $connection_options);
 
-    // We don't need a specific PDOStatement class here, we simulate it below.
-    $this->statementClass = NULL;
-
     // This driver defaults to transaction support, except if explicitly passed FALSE.
     $this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;
 
@@ -244,14 +241,71 @@ public static function sqlFunctionRegexp($string, $pattern) {
   }
 
   /**
-   * SQLite-specific implementation of DatabaseConnection::prepare().
-   *
-   * We don't use prepared statements at all at this stage. We just create
-   * a Statement object, that will create a PDOStatement
-   * using the semi-private PDOPrepare() method below.
+   * {@inheritdoc}
    */
-  public function prepare($statement, array $driver_options = array()) {
-    return new Statement($this->connection, $this, $statement, $driver_options);
+  protected function expandArguments(&$query, &$args) {
+    $modified = parent::expandArguments($query, $args);
+
+    // The PDO SQLite driver always replaces placeholders with strings, which
+    // breaks numeric expressions (e.g., COUNT(*) >= :count). Replace numeric
+    // placeholders in the query to work around this bug.
+    // @see http://bugs.php.net/bug.php?id=45259
+    if (empty($args)) {
+      return $modified;
+    }
+    // Check if $args is a simple numeric array.
+    if (range(0, count($args) - 1) === array_keys($args)) {
+      // In that case, we have unnamed placeholders.
+      $count = 0;
+      $new_args = array();
+      foreach ($args as $value) {
+        if (is_float($value) || is_int($value) || is_numeric($value)) {
+          if (is_float($value)) {
+            // Force the conversion to float so as not to loose precision
+            // in the automatic cast.
+            $value = sprintf('%F', $value);
+          }
+          $query = substr_replace($query, $value, strpos($query, '?'), 1);
+        }
+        else {
+          $placeholder = ':db_statement_placeholder_' . $count++;
+          $query = substr_replace($query, $placeholder, strpos($query, '?'), 1);
+          $new_args[$placeholder] = $value;
+        }
+      }
+      $args = $new_args;
+      $modified = TRUE;
+    }
+    // Otherwise this is using named placeholders.
+    else {
+      foreach ($args as $placeholder => $value) {
+        if (is_float($value) || is_int($value) || is_numeric($value)) {
+          if (is_float($value)) {
+            // Force the conversion to float so as not to loose precision
+            // in the automatic cast.
+            $value = sprintf('%F', $value);
+          }
+
+          // We will remove this placeholder from the query as PDO throws an
+          // exception if the number of placeholders in the query and the
+          // arguments does not match.
+          unset($args[$placeholder]);
+          // PDO allows placeholders to not be prefixed by a colon. See
+          // http://marc.info/?l=php-internals&m=111234321827149&w=2 for
+          // more.
+          if ($placeholder[0] != ':') {
+            $placeholder = ":$placeholder";
+          }
+          // When replacing the placeholders, make sure we search for the
+          // exact placeholder. For example, if searching for
+          // ':db_placeholder_1', do not replace ':db_placeholder_11'.
+          $query = preg_replace('/' . preg_quote($placeholder, '/') . '\b/', $value, $query);
+
+          $modified = TRUE;
+        }
+      }
+    }
+    return $modified;
   }
 
   public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Statement.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Statement.php
deleted file mode 100644
index 0be036d..0000000
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Statement.php
+++ /dev/null
@@ -1,146 +0,0 @@
-<?php
-
-/**
- * @file
- * Definition of Drupal\Core\Database\Driver\sqlite\Statement
- */
-
-namespace Drupal\Core\Database\Driver\sqlite;
-
-use Drupal\Core\Database\StatementPrefetch;
-use Drupal\Core\Database\StatementInterface;
-
-/**
- * Specific SQLite implementation of DatabaseConnection.
- *
- * The PDO SQLite driver only closes SELECT statements when the PDOStatement
- * destructor is called and SQLite does not allow data change (INSERT,
- * UPDATE etc) on a table which has open SELECT statements. This is a
- * user-space mock of PDOStatement that buffers all the data and doesn't
- * have those limitations.
- */
-class Statement extends StatementPrefetch implements \Iterator, StatementInterface {
-
-  /**
-   * SQLite specific implementation of getStatement().
-   *
-   * The PDO SQLite layer doesn't replace numeric placeholders in queries
-   * correctly, and this makes numeric expressions (such as COUNT(*) >= :count)
-   * fail. We replace numeric placeholders in the query ourselves to work
-   * around this bug.
-   *
-   * See http://bugs.php.net/bug.php?id=45259 for more details.
-   */
-  protected function getStatement($query, &$args = array()) {
-    if (count($args)) {
-      // Check if $args is a simple numeric array.
-      if (range(0, count($args) - 1) === array_keys($args)) {
-        // In that case, we have unnamed placeholders.
-        $count = 0;
-        $new_args = array();
-        foreach ($args as $value) {
-          if (is_float($value) || is_int($value)) {
-            if (is_float($value)) {
-              // Force the conversion to float so as not to loose precision
-              // in the automatic cast.
-              $value = sprintf('%F', $value);
-            }
-            $query = substr_replace($query, $value, strpos($query, '?'), 1);
-          }
-          else {
-            $placeholder = ':db_statement_placeholder_' . $count++;
-            $query = substr_replace($query, $placeholder, strpos($query, '?'), 1);
-            $new_args[$placeholder] = $value;
-          }
-        }
-        $args = $new_args;
-      }
-      else {
-        // Else, this is using named placeholders.
-        foreach ($args as $placeholder => $value) {
-          if (is_float($value) || is_int($value)) {
-            if (is_float($value)) {
-              // Force the conversion to float so as not to loose precision
-              // in the automatic cast.
-              $value = sprintf('%F', $value);
-            }
-
-            // We will remove this placeholder from the query as PDO throws an
-            // exception if the number of placeholders in the query and the
-            // arguments does not match.
-            unset($args[$placeholder]);
-            // PDO allows placeholders to not be prefixed by a colon. See
-            // http://marc.info/?l=php-internals&m=111234321827149&w=2 for
-            // more.
-            if ($placeholder[0] != ':') {
-              $placeholder = ":$placeholder";
-            }
-            // When replacing the placeholders, make sure we search for the
-            // exact placeholder. For example, if searching for
-            // ':db_placeholder_1', do not replace ':db_placeholder_11'.
-            $query = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $query);
-          }
-        }
-      }
-    }
-
-    return $this->dbh->prepare($query);
-  }
-
-  public function execute($args = array(), $options = array()) {
-    try {
-      $return = parent::execute($args, $options);
-    }
-    catch (\PDOException $e) {
-      if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
-        // The schema has changed. SQLite specifies that we must resend the query.
-        $return = parent::execute($args, $options);
-      }
-      else {
-        // Rethrow the exception.
-        throw $e;
-      }
-    }
-
-    // In some weird cases, SQLite will prefix some column names by the name
-    // of the table. We post-process the data, by renaming the column names
-    // using the same convention as MySQL and PostgreSQL.
-    $rename_columns = array();
-    foreach ($this->columnNames as $k => $column) {
-      // In some SQLite versions, SELECT DISTINCT(field) will return "(field)"
-      // instead of "field".
-      if (preg_match("/^\((.*)\)$/", $column, $matches)) {
-        $rename_columns[$column] = $matches[1];
-        $this->columnNames[$k] = $matches[1];
-        $column = $matches[1];
-      }
-
-      // Remove "table." prefixes.
-      if (preg_match("/^.*\.(.*)$/", $column, $matches)) {
-        $rename_columns[$column] = $matches[1];
-        $this->columnNames[$k] = $matches[1];
-      }
-    }
-    if ($rename_columns) {
-      // DatabaseStatementPrefetch already extracted the first row,
-      // put it back into the result set.
-      if (isset($this->currentRow)) {
-        $this->data[0] = &$this->currentRow;
-      }
-
-      // Then rename all the columns across the result set.
-      foreach ($this->data as $k => $row) {
-        foreach ($rename_columns as $old_column => $new_column) {
-          $this->data[$k][$new_column] = $this->data[$k][$old_column];
-          unset($this->data[$k][$old_column]);
-        }
-      }
-
-      // Finally, extract the first row again.
-      $this->currentRow = $this->data[0];
-      unset($this->data[0]);
-    }
-
-    return $return;
-  }
-}
diff --git a/core/lib/Drupal/Core/Database/StatementPrefetch.php b/core/lib/Drupal/Core/Database/StatementPrefetch.php
deleted file mode 100644
index c32d94a..0000000
--- a/core/lib/Drupal/Core/Database/StatementPrefetch.php
+++ /dev/null
@@ -1,512 +0,0 @@
-<?php
-
-/**
- * @file
- * Definition of Drupal\Core\Database\StatementPrefetch
- */
-
-namespace Drupal\Core\Database;
-
-use Drupal\Core\Database\Connection;
-
-/**
- * An implementation of StatementInterface that prefetches all data.
- *
- * This class behaves very similar to a \PDOStatement but as it always fetches
- * every row it is possible to manipulate those results.
- */
-class StatementPrefetch implements \Iterator, StatementInterface {
-
-  /**
-   * The query string.
-   *
-   * @var string
-   */
-  protected $queryString;
-
-  /**
-   * Driver-specific options. Can be used by child classes.
-   *
-   * @var Array
-   */
-  protected $driverOptions;
-
-  /**
-   * Reference to the database connection object for this statement.
-   *
-   * This is part of the public interface of \PDOStatement.
-   *
-   * @var \PDO
-   */
-  public $dbh;
-
-  /**
-   * Reference to the Drupal database connection object for this statement.
-   *
-   * @var \Drupal\Core\Database\Connection
-   */
-  protected $connection;
-
-  /**
-   * Main data store.
-   *
-   * @var Array
-   */
-  protected $data = array();
-
-  /**
-   * The current row, retrieved in \PDO::FETCH_ASSOC format.
-   *
-   * @var Array
-   */
-  protected $currentRow = NULL;
-
-  /**
-   * The key of the current row.
-   *
-   * @var int
-   */
-  protected $currentKey = NULL;
-
-  /**
-   * The list of column names in this result set.
-   *
-   * @var Array
-   */
-  protected $columnNames = NULL;
-
-  /**
-   * The number of rows affected by the last query.
-   *
-   * @var int
-   */
-  protected $rowCount = NULL;
-
-  /**
-   * The number of rows in this result set.
-   *
-   * @var int
-   */
-  protected $resultRowCount = 0;
-
-  /**
-   * Holds the current fetch style (which will be used by the next fetch).
-   * @see \PDOStatement::fetch()
-   *
-   * @var int
-   */
-  protected $fetchStyle = \PDO::FETCH_OBJ;
-
-  /**
-   * Holds supplementary current fetch options (which will be used by the next fetch).
-   *
-   * @var Array
-   */
-  protected $fetchOptions = array(
-    'class' => 'stdClass',
-    'constructor_args' => array(),
-    'object' => NULL,
-    'column' => 0,
-  );
-
-  /**
-   * Holds the default fetch style.
-   *
-   * @var int
-   */
-  protected $defaultFetchStyle = \PDO::FETCH_OBJ;
-
-  /**
-   * Holds supplementary default fetch options.
-   *
-   * @var Array
-   */
-  protected $defaultFetchOptions = array(
-    'class' => 'stdClass',
-    'constructor_args' => array(),
-    'object' => NULL,
-    'column' => 0,
-  );
-
-  /**
-   * Is rowCount() execution allowed.
-   *
-   * @var bool
-   */
-  public $allowRowCount = FALSE;
-
-  public function __construct(\PDO $dbh, Connection $connection, $query, array $driver_options = array()) {
-    $this->dbh = $dbh;
-    $this->connection = $connection;
-    $this->queryString = $query;
-    $this->driverOptions = $driver_options;
-  }
-
-  /**
-   * Executes a prepared statement.
-   *
-   * @param $args
-   *   An array of values with as many elements as there are bound parameters in the SQL statement being executed.
-   * @param $options
-   *   An array of options for this query.
-   * @return
-   *   TRUE on success, or FALSE on failure.
-   */
-  public function execute($args = array(), $options = array()) {
-    if (isset($options['fetch'])) {
-      if (is_string($options['fetch'])) {
-        // Default to an object. Note: db fields will be added to the object
-        // before the constructor is run. If you need to assign fields after
-        // the constructor is run, see http://drupal.org/node/315092.
-        $this->setFetchMode(\PDO::FETCH_CLASS, $options['fetch']);
-      }
-      else {
-        $this->setFetchMode($options['fetch']);
-      }
-    }
-
-    $logger = $this->connection->getLogger();
-    if (!empty($logger)) {
-      $query_start = microtime(TRUE);
-    }
-
-    // Prepare the query.
-    $statement = $this->getStatement($this->queryString, $args);
-    if (!$statement) {
-      $this->throwPDOException();
-    }
-
-    $return = $statement->execute($args);
-    if (!$return) {
-      $this->throwPDOException();
-    }
-
-    if ($options['return'] == Database::RETURN_AFFECTED) {
-      $this->rowCount = $statement->rowCount();
-    }
-    // Fetch all the data from the reply, in order to release any lock
-    // as soon as possible.
-    $this->data = $statement->fetchAll(\PDO::FETCH_ASSOC);
-    // Destroy the statement as soon as possible. See
-    // DatabaseConnection_sqlite::PDOPrepare() for explanation.
-    unset($statement);
-
-    $this->resultRowCount = count($this->data);
-
-    if ($this->resultRowCount) {
-      $this->columnNames = array_keys($this->data[0]);
-    }
-    else {
-      $this->columnNames = array();
-    }
-
-    if (!empty($logger)) {
-      $query_end = microtime(TRUE);
-      $logger->log($this, $args, $query_end - $query_start);
-    }
-
-    // Initialize the first row in $this->currentRow.
-    $this->next();
-
-    return $return;
-  }
-
-  /**
-   * Throw a PDO Exception based on the last PDO error.
-   */
-  protected function throwPDOException() {
-    $error_info = $this->dbh->errorInfo();
-    // We rebuild a message formatted in the same way as PDO.
-    $exception = new \PDOException("SQLSTATE[" . $error_info[0] . "]: General error " . $error_info[1] . ": " . $error_info[2]);
-    $exception->errorInfo = $error_info;
-    throw $exception;
-  }
-
-  /**
-   * Grab a PDOStatement object from a given query and its arguments.
-   *
-   * Some drivers (including SQLite) will need to perform some preparation
-   * themselves to get the statement right.
-   *
-   * @param $query
-   *   The query.
-   * @param array $args
-   *   An array of arguments.
-   * @return \PDOStatement
-   *   A PDOStatement object.
-   */
-  protected function getStatement($query, &$args = array()) {
-    return $this->dbh->prepare($query);
-  }
-
-  /**
-   * Return the object's SQL query string.
-   */
-  public function getQueryString() {
-    return $this->queryString;
-  }
-
-  /**
-   * @see \PDOStatement::setFetchMode()
-   */
-  public function setFetchMode($fetchStyle, $a2 = NULL, $a3 = NULL) {
-    $this->defaultFetchStyle = $fetchStyle;
-    switch ($fetchStyle) {
-      case \PDO::FETCH_CLASS:
-        $this->defaultFetchOptions['class'] = $a2;
-        if ($a3) {
-          $this->defaultFetchOptions['constructor_args'] = $a3;
-        }
-        break;
-      case \PDO::FETCH_COLUMN:
-        $this->defaultFetchOptions['column'] = $a2;
-        break;
-      case \PDO::FETCH_INTO:
-        $this->defaultFetchOptions['object'] = $a2;
-        break;
-    }
-
-    // Set the values for the next fetch.
-    $this->fetchStyle = $this->defaultFetchStyle;
-    $this->fetchOptions = $this->defaultFetchOptions;
-  }
-
-  /**
-   * Return the current row formatted according to the current fetch style.
-   *
-   * This is the core method of this class. It grabs the value at the current
-   * array position in $this->data and format it according to $this->fetchStyle
-   * and $this->fetchMode.
-   *
-   * @return
-   *  The current row formatted as requested.
-   */
-  public function current() {
-    if (isset($this->currentRow)) {
-      switch ($this->fetchStyle) {
-        case \PDO::FETCH_ASSOC:
-          return $this->currentRow;
-        case \PDO::FETCH_BOTH:
-          // \PDO::FETCH_BOTH returns an array indexed by both the column name
-          // and the column number.
-          return $this->currentRow + array_values($this->currentRow);
-        case \PDO::FETCH_NUM:
-          return array_values($this->currentRow);
-        case \PDO::FETCH_LAZY:
-          // We do not do lazy as everything is fetched already. Fallback to
-          // \PDO::FETCH_OBJ.
-        case \PDO::FETCH_OBJ:
-          return (object) $this->currentRow;
-        case \PDO::FETCH_CLASS | \PDO::FETCH_CLASSTYPE:
-          $class_name = array_unshift($this->currentRow);
-          // Deliberate no break.
-        case \PDO::FETCH_CLASS:
-          if (!isset($class_name)) {
-            $class_name = $this->fetchOptions['class'];
-          }
-          if (count($this->fetchOptions['constructor_args'])) {
-            $reflector = new \ReflectionClass($class_name);
-            $result = $reflector->newInstanceArgs($this->fetchOptions['constructor_args']);
-          }
-          else {
-            $result = new $class_name();
-          }
-          foreach ($this->currentRow as $k => $v) {
-            $result->$k = $v;
-          }
-          return $result;
-        case \PDO::FETCH_INTO:
-          foreach ($this->currentRow as $k => $v) {
-            $this->fetchOptions['object']->$k = $v;
-          }
-          return $this->fetchOptions['object'];
-        case \PDO::FETCH_COLUMN:
-          if (isset($this->columnNames[$this->fetchOptions['column']])) {
-            return $this->currentRow[$k][$this->columnNames[$this->fetchOptions['column']]];
-          }
-          else {
-            return;
-          }
-      }
-    }
-  }
-
-  /* Implementations of Iterator. */
-
-  public function key() {
-    return $this->currentKey;
-  }
-
-  public function rewind() {
-    // Nothing to do: our DatabaseStatement can't be rewound.
-  }
-
-  public function next() {
-    if (!empty($this->data)) {
-      $this->currentRow = reset($this->data);
-      $this->currentKey = key($this->data);
-      unset($this->data[$this->currentKey]);
-    }
-    else {
-      $this->currentRow = NULL;
-    }
-  }
-
-  public function valid() {
-    return isset($this->currentRow);
-  }
-
-  /* Implementations of StatementInterface. */
-
-  public function rowCount() {
-    return $this->rowCount;
-  }
-
-  public function fetch($fetch_style = NULL, $cursor_orientation = \PDO::FETCH_ORI_NEXT, $cursor_offset = NULL) {
-    if (isset($this->currentRow)) {
-      // Set the fetch parameter.
-      $this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
-      $this->fetchOptions = $this->defaultFetchOptions;
-
-      // Grab the row in the format specified above.
-      $return = $this->current();
-      // Advance the cursor.
-      $this->next();
-
-      // Reset the fetch parameters to the value stored using setFetchMode().
-      $this->fetchStyle = $this->defaultFetchStyle;
-      $this->fetchOptions = $this->defaultFetchOptions;
-      return $return;
-    }
-    else {
-      return FALSE;
-    }
-  }
-
-  public function fetchColumn($index = 0) {
-    if (isset($this->currentRow) && isset($this->columnNames[$index])) {
-      // We grab the value directly from $this->data, and format it.
-      $return = $this->currentRow[$this->columnNames[$index]];
-      $this->next();
-      return $return;
-    }
-    else {
-      return FALSE;
-    }
-  }
-
-  public function fetchField($index = 0) {
-    return $this->fetchColumn($index);
-  }
-
-  public function fetchObject($class_name = NULL, $constructor_args = array()) {
-    if (isset($this->currentRow)) {
-      if (!isset($class_name)) {
-        // Directly cast to an object to avoid a function call.
-        $result = (object) $this->currentRow;
-      }
-      else {
-        $this->fetchStyle = \PDO::FETCH_CLASS;
-        $this->fetchOptions = array('constructor_args' => $constructor_args);
-        // Grab the row in the format specified above.
-        $result = $this->current();
-        // Reset the fetch parameters to the value stored using setFetchMode().
-        $this->fetchStyle = $this->defaultFetchStyle;
-        $this->fetchOptions = $this->defaultFetchOptions;
-      }
-
-      $this->next();
-
-      return $result;
-    }
-    else {
-      return FALSE;
-    }
-  }
-
-  public function fetchAssoc() {
-    if (isset($this->currentRow)) {
-      $result = $this->currentRow;
-      $this->next();
-      return $result;
-    }
-    else {
-      return FALSE;
-    }
-  }
-
-  public function fetchAll($fetch_style = NULL, $fetch_column = NULL, $constructor_args = NULL) {
-    $this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
-    $this->fetchOptions = $this->defaultFetchOptions;
-    if (isset($fetch_column)) {
-      $this->fetchOptions['column'] = $fetch_column;
-    }
-    if (isset($constructor_args)) {
-      $this->fetchOptions['constructor_args'] = $constructor_args;
-    }
-
-    $result = array();
-    // Traverse the array as PHP would have done.
-    while (isset($this->currentRow)) {
-      // Grab the row in the format specified above.
-      $result[] = $this->current();
-      $this->next();
-    }
-
-    // Reset the fetch parameters to the value stored using setFetchMode().
-    $this->fetchStyle = $this->defaultFetchStyle;
-    $this->fetchOptions = $this->defaultFetchOptions;
-    return $result;
-  }
-
-  public function fetchCol($index = 0) {
-    if (isset($this->columnNames[$index])) {
-      $result = array();
-      // Traverse the array as PHP would have done.
-      while (isset($this->currentRow)) {
-        $result[] = $this->currentRow[$this->columnNames[$index]];
-        $this->next();
-      }
-      return $result;
-    }
-    else {
-      return array();
-    }
-  }
-
-  public function fetchAllKeyed($key_index = 0, $value_index = 1) {
-    if (!isset($this->columnNames[$key_index]) || !isset($this->columnNames[$value_index]))
-      return array();
-
-    $key = $this->columnNames[$key_index];
-    $value = $this->columnNames[$value_index];
-
-    $result = array();
-    // Traverse the array as PHP would have done.
-    while (isset($this->currentRow)) {
-      $result[$this->currentRow[$key]] = $this->currentRow[$value];
-      $this->next();
-    }
-    return $result;
-  }
-
-  public function fetchAllAssoc($key, $fetch_style = NULL) {
-    $this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
-    $this->fetchOptions = $this->defaultFetchOptions;
-
-    $result = array();
-    // Traverse the array as PHP would have done.
-    while (isset($this->currentRow)) {
-      // Grab the row in its raw \PDO::FETCH_ASSOC format.
-      $result_row = $this->current();
-      $result[$this->currentRow[$key]] = $result_row;
-      $this->next();
-    }
-
-    // Reset the fetch parameters to the value stored using setFetchMode().
-    $this->fetchStyle = $this->defaultFetchStyle;
-    $this->fetchOptions = $this->defaultFetchOptions;
-    return $result;
-  }
-
-}
-- 
1.7.11.msysgit.1


From 12a94d0937f20a492b460b4d92ad421e91f980d2 Mon Sep 17 00:00:00 2001
From: sun <sun@unleashedmind.com>
Date: Wed, 6 Aug 2014 01:37:10 +0200
Subject: [PATCH 2/6] Issue #2318191 by sun: Fixed SQLite Insert query does
 not account for INSERT FROM ... SELECT.

---
 core/lib/Drupal/Core/Database/Driver/sqlite/Insert.php | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Insert.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Insert.php
index 3a0bcaa..8882fcd 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Insert.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Insert.php
@@ -22,7 +22,7 @@ public function execute() {
     if (!$this->preExecute()) {
       return NULL;
     }
-    if (count($this->insertFields)) {
+    if (count($this->insertFields) || !empty($this->fromQuery)) {
       return parent::execute();
     }
     else {
@@ -35,7 +35,10 @@ public function __toString() {
     $comments = $this->connection->makeComment($this->comments);
 
     // Produce as many generic placeholders as necessary.
-    $placeholders = array_fill(0, count($this->insertFields), '?');
+    $placeholders = array();
+    if (!empty($this->insertFields)) {
+      $placeholders = array_fill(0, count($this->insertFields), '?');
+    }
 
     // If we're selecting from a SelectQuery, finish building the query and
     // pass it back, as any remaining options are irrelevant.
-- 
1.7.11.msysgit.1


From dc0d23d035ba0666f750e8b09b5be7b7ef267fad Mon Sep 17 00:00:00 2001
From: sun <sun@unleashedmind.com>
Date: Wed, 6 Aug 2014 01:35:32 +0200
Subject: [PATCH 3/6] Issue #2318191 by sun: Fixed SQLite: Wrong parameter
 order in REGEXP user function.

---
 core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
index 4e9807c..866d499 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
@@ -234,10 +234,16 @@ public static function sqlFunctionRand($seed = NULL) {
   /**
    * SQLite compatibility implementation for the REGEXP SQL operator.
    *
-   * The REGEXP operator is a special syntax for the regexp() user function.
+   * The REGEXP operator is natively known, but not implemented by default.
+   *
+   * @see http://www.sqlite.org/lang_expr.html#regexp
    */
-  public static function sqlFunctionRegexp($string, $pattern) {
-    return preg_match('#' . str_replace('#', '\#', $pattern) . '#i', $string);
+  public static function sqlFunctionRegexp($pattern, $subject) {
+    // preg_quote() cannot be used here, since $pattern may contain reserved
+    // regular expression characters already (such as ^, $, etc). Therefore,
+    // use a rare character as PCRE delimiter.
+    $pattern = '#' . addcslashes($pattern, '#') . '#i';
+    return preg_match($pattern, $subject);
   }
 
   /**
-- 
1.7.11.msysgit.1


From 887ff65a81db6d86f63171ab44fc6d36fa9b1254 Mon Sep 17 00:00:00 2001
From: sun <sun@unleashedmind.com>
Date: Sun, 3 Aug 2014 22:08:36 +0200
Subject: [PATCH 4/6] Issue #2318191 by sun: Fixed SQLite does not interpret
 '\_' as string literal in LIKE without ESCAPE.

MySQL breaks on LIKE ... ESCAPE '\', so use a proper Select query builder to be portable.
---
 core/lib/Drupal/Core/Config/DatabaseStorage.php | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/core/lib/Drupal/Core/Config/DatabaseStorage.php b/core/lib/Drupal/Core/Config/DatabaseStorage.php
index 20e5f1b..2c512dc 100644
--- a/core/lib/Drupal/Core/Config/DatabaseStorage.php
+++ b/core/lib/Drupal/Core/Config/DatabaseStorage.php
@@ -269,10 +269,11 @@ public function decode($raw) {
    */
   public function listAll($prefix = '') {
     try {
-      return $this->connection->query('SELECT name FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND name LIKE :name', array(
-        ':collection' => $this->collection,
-        ':name' => $this->connection->escapeLike($prefix) . '%',
-      ), $this->options)->fetchCol();
+      $select = $this->connection->select($this->table, 'c', $this->options)
+        ->fields('c', array('name'))
+        ->condition('collection', $this->collection)
+        ->condition('name', $this->connection->escapeLike($prefix) . '%', 'LIKE');
+      return $select->execute()->fetchCol();
     }
     catch (\Exception $e) {
       return array();
-- 
1.7.11.msysgit.1


From 09606302fa5419dac96c06319b98df2867708edf Mon Sep 17 00:00:00 2001
From: sun <sun@unleashedmind.com>
Date: Mon, 4 Aug 2014 21:15:11 +0200
Subject: [PATCH 5/6] Issue #2318191 by sun: Fixed SQLite does not support
 CONCAT_WS().

---
 .../Core/Database/Driver/sqlite/Connection.php       | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
index 866d499..39a2a41 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
@@ -119,6 +119,7 @@ public static function open(array &$connection_options = array()) {
     $pdo->sqliteCreateFunction('length', 'strlen', 1);
     $pdo->sqliteCreateFunction('md5', 'md5', 1);
     $pdo->sqliteCreateFunction('concat', array(__CLASS__, 'sqlFunctionConcat'));
+    $pdo->sqliteCreateFunction('concat_ws', array(__CLASS__, 'sqlFunctionConcatWs'));
     $pdo->sqliteCreateFunction('substring', array(__CLASS__, 'sqlFunctionSubstring'), 3);
     $pdo->sqliteCreateFunction('substring_index', array(__CLASS__, 'sqlFunctionSubstringIndex'), 3);
     $pdo->sqliteCreateFunction('rand', array(__CLASS__, 'sqlFunctionRand'));
@@ -197,6 +198,25 @@ public static function sqlFunctionConcat() {
   }
 
   /**
+   * SQLite compatibility implementation for the CONCAT_WS() SQL function.
+   *
+   * @see http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat-ws
+   */
+  public static function sqlFunctionConcatWs() {
+    $args = func_get_args();
+    $separator = array_shift($args);
+    // If the separator is NULL, the result is NULL.
+    if ($separator === FALSE || is_null($separator)) {
+      return NULL;
+    }
+    // Skip any NULL values after the separator argument.
+    $args = array_filter($args, function ($value) {
+      return !is_null($value);
+    });
+    return implode($separator, $args);
+  }
+
+  /**
    * SQLite compatibility implementation for the SUBSTRING() SQL function.
    */
   public static function sqlFunctionSubstring($string, $from, $length) {
-- 
1.7.11.msysgit.1


From 5ce14c24ee8880e1695839d2663aeb2a045f8432 Mon Sep 17 00:00:00 2001
From: sun <sun@unleashedmind.com>
Date: Tue, 5 Aug 2014 21:23:23 +0200
Subject: [PATCH 6/6] Issue #2318191 by sun: Updated Views Date Handler for
 SQLite.

SQLite does not support advanced date/calendar operations (such as identifying 2000-01-01 as the 52nd week of 1999).
---
 core/modules/views/src/Plugin/views/query/Sql.php  | 15 ++++++++++++--
 .../views/src/Tests/Handler/ArgumentDateTest.php   | 23 +++++++++++++---------
 2 files changed, 27 insertions(+), 11 deletions(-)

diff --git a/core/modules/views/src/Plugin/views/query/Sql.php b/core/modules/views/src/Plugin/views/query/Sql.php
index 25b1a23..4296196 100644
--- a/core/modules/views/src/Plugin/views/query/Sql.php
+++ b/core/modules/views/src/Plugin/views/query/Sql.php
@@ -1641,7 +1641,7 @@ public function getDateField($field) {
         break;
       case 'sqlite':
         if (!empty($offset)) {
-          $field = "($field + '$offset_seconds')";
+          $field = "($field + $offset_seconds)";
         }
         break;
     }
@@ -1755,7 +1755,18 @@ public function getDateFormat($field, $format) {
           'A' => '',
         );
         $format = strtr($format, $replace);
-        return "strftime('$format', $field, 'unixepoch')";
+        $expression = "strftime('$format', $field, 'unixepoch')";
+        // The expression yields a string, but the comparison value is an
+        // integer in case the comparison value is a float, integer, or numeric.
+        // All of the above SQLite format tokens only produce integers. However,
+        // the given $format may contain 'Y-m-d', which results in a string.
+        // @see \Drupal\Core\Database\Driver\sqlite\Connection::expandArguments()
+        // @see http://www.sqlite.org/lang_datefunc.html
+        // @see http://www.sqlite.org/lang_expr.html#castexpr
+        if (preg_match('/^(?:%\w)+$/', $format)) {
+          $expression = "CAST($expression AS NUMERIC)";
+        }
+        return $expression;
     }
   }
 
diff --git a/core/modules/views/src/Tests/Handler/ArgumentDateTest.php b/core/modules/views/src/Tests/Handler/ArgumentDateTest.php
index 4c66e79..f6ba131 100644
--- a/core/modules/views/src/Tests/Handler/ArgumentDateTest.php
+++ b/core/modules/views/src/Tests/Handler/ArgumentDateTest.php
@@ -163,15 +163,20 @@ public function testWeekHandler() {
       ->execute();
 
     $view = Views::getView('test_argument_date');
-    $view->setDisplay('embed_3');
-    // The first jan 2000 was still in the last week of the previous year.
-    $this->executeView($view, array(52));
-    $expected = array();
-    $expected[] = array('id' => 1);
-    $expected[] = array('id' => 2);
-    $expected[] = array('id' => 3);
-    $this->assertIdenticalResultset($view, $expected, $this->columnMap);
-    $view->destroy();
+
+    // SQLite does not support advanced date operations (such as interpreting
+    // 2000-01-01 as the 52nd week of 1999).
+    if ($this->container->get('database')->driver() !== 'sqlite') {
+      $view->setDisplay('embed_3');
+      // The first jan 2000 was still in the last week of the previous year.
+      $this->executeView($view, array(52));
+      $expected = array();
+      $expected[] = array('id' => 1);
+      $expected[] = array('id' => 2);
+      $expected[] = array('id' => 3);
+      $this->assertIdenticalResultset($view, $expected, $this->columnMap);
+      $view->destroy();
+    }
 
     $view->setDisplay('embed_3');
     $this->executeView($view, array('02'));
-- 
1.7.11.msysgit.1

