I know db_select and Drupal's Database Abstraction Layer work across database implementations as long as there is a driver (mysql, postgresql and sqlite drivers included in core). But what about db_query? Should I patch contributed modules to make sure they work with sqlite?


Any function that is part of the database abstraction layer in Drupal 7 works with every database engine for which there are the necessary classes to work with that database engine.

If you look at the code of db_query(), you will notice it is generic enough to work with every database engine.

function db_query($query, array $args = array(), array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';

  return Database::getConnection($options['target'])->query($query, $args, $options);

This code is not different from the code executed by db_select().

function db_select($table, $alias = NULL, array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  return Database::getConnection($options['target'])->select($table, $alias, $options);

If you compare those functions with the code executed from db_delete(), you will notice the functions are essentially wrappers around Database::getConnection().

function db_delete($table, array $options = array()) {
  if (empty($options['target']) || $options['target'] == 'slave') {
    $options['target'] = 'default';
  return Database::getConnection($options['target'])->delete($table, $options);

It is Database::getConnection() that, indirectly, builds the object necessary to execute the queries in the database engine, using the following code.

  $driver_class = 'DatabaseConnection_' . $driver;
  require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
  $new_connection = new $driver_class(self::$databaseInfo[$key][$target]);

As SQLite is supported in Drupal 7, db_query() doesn't need to be altered to execute optimized code for SQLite, as the code that it is optimized for that database engine is already contained in the DatabaseConnection_sqlite.


db_query works for all databases, see http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.