When to use db_rewrite_sql

For many site developers who haven't delved into the node access mechanism, the question arises- when do I need to use db_rewrite_sql in my queries?

The answer depends on whether you are writing a snippet to put in a single page/block on your specific site, or whether you are writing core or contributions module code that's supposed to be generally usable.

In the first case, if you are not using any access control modules or similar to control who can see content, then it may not be necessary (or even useful), but you may want to use it anyhow in case you install access control in the future.

In the latter case, you should use it essentially any time you are making a query, especially any content-related query (node, terms, comment, etc). The exception would be for queries doing internal module work but not showing any content to users (e.g. a cron task), or perhaps queries for administrative pages where the user is expected to already have full privileges and/or it is necessary to show an unfiltered list.

To get a better sense of this, look through the core code and observe when and where it is used. Note that for non-node queries you'll need to specify the table being used.

Note: in Drupal 4.6.x and before, node_load() would pass its arguments though db_rewrite_sql. In 4.7.x and later this is not done in order to insure that all nodes are indexed for searching.

 
 

Drupal is a registered trademark of Dries Buytaert.