How to return a DatabaseStatementBase object I have a method that extends the execute() method used in the Drupal 7 database abstraction layer.

When used with db_query, such as:

$result = my_extended_db_query("SELECT * FROM {node} WHERE nid&lt;100")-&gt;execute();


$result holds a DatabaseStatementBase object, whether there are resulting rows or not. However, following:

return $result;


the calling function receives an empty array if there had been no query results, instead of a DatabaseStatementBase object. Because of this, ->fetchAll() fails because it is attempting to operate on a non-object.

How do I get my return to arrive as the same object is started as?

The method:

public function execute() {
$sql = $this-&gt;sql;
switch ($this-&gt;function) {
  case 'db_query':
    if ($this-&gt;args) {
      $args = $this-&gt;args;
      uksort($args,"si_stats_sort_by_length");
      foreach($args as $name =&gt; $value) {
        $sql = str_replace("{" . $name . "}",$value,$sql);
        if (is_array($value)) {
          $sql = str_replace($name,"('" . implode("', '",$value) . "')",$sql);
        } else {
          $sql = str_replace($name,"'" . str_replace("'","''",$value) . "'",$sql);
        }
      }
      try {
        $query = db_query($sql);
      }
      catch (Exception $e) {
        // log the error
        $msg = $e-&gt;getMessage() . "\n";
        $msg .= $e-&gt;getTraceAsString() . "\n";
        mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
      }
      return $query;
    } else {
      try {
        $query = db_query($sql);
      }
      catch (Exception $e) {
        // log the error
        $msg = $e-&gt;getMessage() . "\n";
        $msg .= $e-&gt;getTraceAsString() . "\n";
        mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
      }
      return $query;
    }
Bandaid fix, instead of return $query; test to see if the class of $query is of DatabaseStatementBase or else create a new empty instance of that class and return that ... Eg:

if (is_a($query, 'DatabaseStatementBase')) {
   return $query;
} else {
  return $empty = new DatabaseStatementBase(Database::getConnection());
}