Not sure if it is more of a node.module issue or views. In short: drupal runs some $query (generated from views), but not the $query->countQuery().

I have a view with 'node' as base_table, and a relationship with 'comments' and 'authors' twice (once for node and once for comments). I use it to build an activity stream view with nodes and comments. The view worked all right, until I wanted to limit it by rewriting the query:

function MY_views_pre_execute(view $view)  
{
	if ($view->name == 'v_last_all')
	{
		$query = $view->build_info['query'];
		$query->addExpression('IFNULL(comment_node.created, node.created)', 'dt');
		$query->orderBy('dt','DESC');
		$query->range(0,500);
	
		$view->build_info['count_query'] = $query->countQuery();
	}
}

And I get that Exception 'Query tagged for node access but there is no nid'. Remove the line with count_query - it works all right (but with wrong pagination because of the old count_query remaining, of course).

Debugging _node_query_node_access_alter shows that the query causing all the trouble was:

SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM {node} node LEFT JOIN {comment} comment_node ON node.nid = comment_node.nid LEFT JOIN {users} users_node ON node.uid = users_node.uid LEFT JOIN {users} users_comment ON comment_node.uid = users_comment.uid LEFT JOIN {og_membership} og_membership ON node.nid = og_membership.etid AND og_membership.entity_type = :views_join_condition_0 WHERE (( (og_membership.gid = :og_membership_gid2 ) )AND(( (node.status = :db_condition_placeholder_0) ))) LIMIT 500 OFFSET 0) subquery

I see the 'node' in this query all right, but why does _node_query_node_access_alter fail to infer base_table from this query?

The workround i've found is the following:

function MY_views_pre_execute(view $view)  
{
	if ($view->name == 'v_last_all')
	{
		$query = $view->build_info['query'];
		$query->addExpression('IFNULL(comment_node.created, node.created)', 'dt');
		$query->orderBy('dt','DESC');
		$query->range(0,500);
	
		$count_query = $query->countQuery();
		$count_query->addMetaData('base_table', 'node');
		$view->build_info['count_query'] = $count_query;
	}
}

Not the first time this or similar problem appears, but I seem to have found a different issue. As mentioned in https://drupal.org/node/1272786#comment-5179310 , it seems a combination of view, relationships and rewrite sql enabled.
Why drupal can infer base_table from the query itself - but not from the countQuery it generates itself?

Comments

Version: 7.22 » 7.x-dev

Core issues are now filed against the dev versions where changes will be made. Document the specific release you are using in your issue comment. More information about choosing a version.