[development] Converting db_rewrite_sql for D7

Larry Garfield larry at garfieldtech.com
Sun Oct 11 08:46:02 UTC 2009


On Saturday 10 October 2009 5:18:31 pm Nancy Wichmann wrote:
> Does this look reasonable (sorry, I'm not far enough along to actually
> test):
>
> $where[] = sprintf('(r.rid IN (' . $filters['rid_filter']) . ' OR (%d IN ('
> . $filters['rid_filter']) . ' AND n.uid = 0))', DRUPAL_ANONYMOUS_RID);
>
> becomes:
>
> $query->condition(db_or()->condition('r.rid', $filters['rid_filter'],
> 'IN')->condition(DRUPAL_ANONYMOUS_RID, $filters['rid_filter'],
> 'IN')->condition('n.uid', 0);

It's easier to follow if you use the common line breaking convention.  I also 
find it easier to build the OR statement separately most of the time rather 
than trying to inline everything, even though it is possible to inline it all.

Also, according to my IDE both of the above statements are syntax errors. :-)  
I think you're missing parentheses somewhere.  Assuming that this is the 
original query (converted to double-quote syntax because it's easier to read 
in this case):

$where[] = sprintf("(r.rid IN ({$filters['rid_filter']}) OR (%d IN 
({$filters['rid_filter']}) AND n.uid = 0))", DRUPAL_ANONYMOUS_RID);


Then this, I believe, would be the DBTNG version:

$and = db_and()
  ->condition('n.uid', 0)
  ->condition(DRUPAL_ANONYMOUS_RID, $filters['rid_filter'], 'IN');
$or = db_or()
  ->condition('r.rid', $filters['rid_filter'], 'IN')
  ->condition($and);
$query->condition($or);

Which, if you don't want the intermediate variables, would then be:

$query->condition(db_or()
  ->condition('r.rid', $filters['rid_filter'], 'IN')
  ->condition(db_and()
    ->condition('n.uid', 0)
    ->condition(DRUPAL_ANONYMOUS_RID, $filters['rid_filter'], 'IN')
  )
);

(Personally I prefer the first version as I find it easier to read and edit 
later, but both should work.)


-- 
Larry Garfield
larry at garfieldtech.com


More information about the development mailing list