Is using a variable for a find conditions still sql injection safe?

Hi,

I often find in my code, that it is more convenient to build the
condition for a find into a variable before calling the find method.
This can allow parts of the condition to be built up in stages often
dependant upon other conditions.

I am not sure what exactly takes place in the Rails code to eliminate
the risk of sql injection attacks when the condition parameters are
passed in a hash as recommended. eg.

Booking.find(:first, :conditions=>['bookingref_id = :bid',
{:bid=>@bref.id}])

My question therefore is that if I do this instead of the above:

cond=['bookingref_id = :bid', {:bid=>@bref.id}]

Booking.find(:first, :conditions=>cond)

Do I still get protection from sql injection attacks.

The main difference as far as I can see is that @bref.id is evaluated
and saved into :bid when cond is first assigned. Now it could be that
this messes up the checks that are made in the find method But with my
rather limited knowledge, it would seem to me that there is no
difference since I would think that in the first example, @bref_id is
evaluated and assigned to :bid at the point when find is actually
called, and therefore what the find method itself would see would be
exactly the same.

I would be grateful if someone more elightened than me could confirm if
my assumption is correct, or if what I am doing is dangerous?

Many Thanks
Tonypm

tonypm wrote:

Booking.find(:first, :conditions=>['bookingref_id = :bid',
{:bid=>@bref.id}])

My question therefore is that if I do this instead of the above:

cond=['bookingref_id = :bid', {:bid=>@bref.id}]

Booking.find(:first, :conditions=>cond)

Do I still get protection from sql injection attacks.

Yes, that's fine. The magic happens inside the 'find' method.

More generally (as far as I know), methods have no way of knowing
whether you've passed them a literal argument like the first example,
or whether you're passing them a variable, like in the second example.
So as far as the 'find' method is concerned here, those two calls are
exactly equivalent.

Chris

That's what I had hoped was the case.

Many Thanks

Run this query with any non-numeric criteria and ypu will know by your SQL log (you whouls dee Rails quoting your variable value in the query). But the short answer is yes.