You are here

views_show_query.module in Views Show Query 7

File

views_show_query.module
View source
<?php

/**
 * Implements hook_form_FORM_ID_alter().
 */
function views_show_query_form_views_ui_preview_form_alter(&$form, &$form_state, $form_id) {

  // Place new text field before the submit button.
  $button = $form['button'];
  unset($form['button']);
  $form['views_show_query_uid'] = array(
    '#type' => 'textfield',
    '#title' => t('User ID to show final query'),
    '#size' => 4,
  );
  $form['button'] = $button;
}

/**
 * Implements hook_views_preview_info_alter().
 */
function views_show_query_views_preview_info_alter(&$rows, $view) {
  $account = NULL;
  if (isset($view->exposed_input['views_show_query_uid'])) {
    $uid = trim($view->exposed_input['views_show_query_uid']);
    if (is_numeric($uid)) {
      $uid = intval($uid);
      $account = user_load($uid);
    }
  }
  if (empty($account)) {
    return;
  }
  $query = $view->build_info['query'];

  // _node_query_node_access_alter() uses 'account' metadata of the query object to add access checks to SQL.
  $query
    ->addMetaData('account', $account);
  if (method_exists($query, 'preExecute')) {
    if (isset($query->alterTags)) {
      $hooks = array(
        'query',
      );
      foreach ($query->alterTags as $tag => $value) {
        $hooks[] = 'query_' . $tag;
      }
      drupal_alter($hooks, $query);
    }

    // @todo Make preExecute work by providing query not prepared yet.

    //$query->preExecute();
    $sql = (string) $query;
    $quoted = array();
    $connection = Database::getConnection();
    $sql = $connection
      ->prefixTables($sql);
    foreach ((array) $query
      ->arguments() as $key => $val) {
      $quoted[$key] = $connection
        ->quote($val);
    }
    $sql = strtr($sql, $quoted);
    $rows['query'][] = array(
      '<strong>' . t('Final query') . '</strong>',
      '<pre>' . $sql . '</pre>',
    );
  }
}