Last updated March 23, 2011. Created by lukus on November 9, 2006.
Edited by scor, mike booth, webchick, pwolanin. Log in to edit this page.

db_rewrite_sql() in Drupal 6 and hook_query_alter() tagged with 'node_access' in Drupal 7 provide a method for modules to extend your SQL queries. For example, a module which controls access to nodes will need to limit the results of your queries, removing any nodes for which a visitor does not have the required set of access permissions.

If you do not make use of db_rewrite_sql() or hook_query_alter(), access control modules won't be able to modify or extend your SQL queries, and you may inadvertently expose content that is meant to be restricted.

It's good practice to always make use of db_rewrite_sql() or hook_query_alter().

Possible exceptions include:

  • Queries which carry out internal module work, but which aren't responsible for showing content to users (e.g. queries within cron tasks).
  • Queries for administrative pages where it is necessary to show an unfiltered list, and where the user is guaranteed to already have full privileges.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

I had been getting warning messages "Unknown column 'n.nid' in 'on clause' query ..." as soon I installed any node access module. After much angst, I discovered that I had used db_rewrite_sql incorrectly in many places. The function assumes that your query selects from a table aliased as 'n' with a key 'nid'. If this is not the case you should indicate that through the parameters of db_rewrite_sql.

For example if your query is SELECT * FROM content_type_product, you must say something like
db_rewrite_sql("SELECT * FROM content_type_product", "content_type_product").