Skip to content

Instantly share code, notes, and snippets.

@cbeier
Last active August 15, 2017 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbeier/6502769555e74bb3b899fc1aec0260b9 to your computer and use it in GitHub Desktop.
Save cbeier/6502769555e74bb3b899fc1aec0260b9 to your computer and use it in GitHub Desktop.
Drupal 8: Debug Database Query
<?php
namespace Drupal\YOURNAMESPACE\Helper;
use Drupal\Core\Database\Query\SelectInterface;
class DebugQuery {
/**
* Debug a database query and print it out.
*
* @code
* DebugQuery::debug($query);
* @endcode
*
* @param \Drupal\Core\Database\Query\SelectInterface $query
* The query.
* @param bool $replace_arguments
* Replaces the query placeholder with the arguments.
*/
public static function printQuery(SelectInterface $query, $replace_placeholder = TRUE) {
print self::debug($query, $replace_placeholder);
}
/**
* Debug a database query.
*
* @code
* print(DebugQuery::debug($query));
* @endcode
*
* Or with devel installed:
* @code
* dsm(DebugQuery::debug($query));
* @endcode
*
* @param \Drupal\Core\Database\Query\SelectInterface $query
* The query.
* @param bool $replace_arguments
* Replaces the query placeholder with the arguments.
*
* @return string
* The query string.
*/
public static function debug(SelectInterface $query, $replace_placeholder = TRUE) {
$string = (string) $query;
$arguments = $query->arguments();
if ($replace_placeholder && !empty($arguments) && is_array($arguments)) {
foreach ($arguments as $placeholder => &$value) {
if (is_string($value)) {
$value = "'$value'";
}
}
$string = strtr($string, $arguments);
}
$string = str_replace(array('{', '}'), '', $string);
return $string;
}
}
<?php
/**
* Debug a database query.
*
* @code
* print(DebugQuery::debug($query));
* @endcode
*
* Or with devel installed:
* @code
* dsm(DebugQuery::debug($query));
* @endcode
*
* @param \Drupal\Core\Database\Query\SelectInterface $query
* The query.
* @param bool $replace_arguments
* Replaces the query placeholder with the arguments.
*
* @return string
* The query string.
*/
function debug_query($query, $replace_placeholder = TRUE) {
$string = (string) $query;
$arguments = $query->arguments();
if ($replace_placeholder && !empty($arguments) && is_array($arguments)) {
foreach ($arguments as $placeholder => &$value) {
if (is_string($value)) {
$value = "'$value'";
}
}
$string = strtr($string, $arguments);
}
$string = str_replace(array('{', '}'), '', $string);
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment