Drupal - Debug EntityFieldQuery?

It's a wee bit of a hack, but you could add a tag to any EntityFieldQuery you're interested in printing the query for, then implement hook_query_alter() to intercept it when it's a standard SelectQuery, then cast it to string for debugging:

function MYMODULE_query_alter($query) {
  if ($query->hasTag('efq_debug')) {
    dpm((string)$query);
  }
}

$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node')
  ->addTag('efq_debug')
  ->execute();

It's a bit of a hack but does the trick. The output for the above is:

SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type     
AS entity_type
FROM {node} node

Presumably this will also only work when using MySQL as the field storage system.


Rather than rolling your own hook_query_alter() you can let Devel module do the heavy lifting for you by adding the debug tag:

$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node');
  ->addTag('debug')
  ->execute();

This will print the query to screen, just like dpq() would.


Adding to the @Clive answer, which generally prints the query with the placeholder not along with the value. To print the value with the query use the following code under the hook_query_alter.

function hook_query_alter($query) {
  if ($query->hasTag('debug')) {
    $sql = (string)$query;
    $connection = Database::getConnection();
    foreach ((array) $query->arguments() as $key => $val) {
      $quoted[$key] = $connection->quote($val);
    }
    $sql = strtr($sql, $quoted);
    dpm($sql);
  }
}


$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node');
  ->addTag('debug');
  ->execute();

It is not good practice to install a module for the few lines of code. That is why I opted for the aforementioned solution.