General query using ActiveRecord


#1

Problem: Is the following approach SQL injection safe?

I have five filter fields and would like to be able to ask 2**5 = 32
different WHERE clauses with LIKE conditions.

If it is safe, can it be improved or simplified?

cond = “”
cond += AddCond(“flight like”, “%”, @report.flight, “%”)
cond += AddCond(“description like”, “%”, @report.description, “%”)
cond += AddCond(“users.name http://users.name like”, “%”,
@report.pilot,
“%”)
cond += AddCond(“flightdate >=”, “”, @report.fromdate, “”)
cond += AddCond(“flightdate <=”, “”, @report.todate, “”)

if cond=="" then
@reports = Report.find(:all)
else
@reports = Report.find(:all,
:conditions => “1=1” + cond,
:joins => "INNER JOIN Users ON Reports.user_id = Users.id
http://Users.id
")
end

def AddCond(query, prefix, value, suffix)
if value.nil? then
“”
elsif value == “” then
“”
else
" and " + query + " " + Report.quote(prefix + value + suffix)
end
end


#2

Christian Szell: Is it safe?.. Is it safe?
Babe: You’re talking to me?
Christian Szell: Is it safe?
Babe: Is what safe?
Christian Szell: Is it safe?
Babe: I don’t know what you mean. I can’t tell you something’s safe
or not, unless I know specifically
what you’re talking about.
Christian Szell: Is it safe?
Babe: Tell me what the “it” refers to.
Christian Szell: Is it safe?
Babe: Yes, it’s safe, it’s very safe, it’s so safe you wouldn’t
believe it.
Christian Szell: Is it safe?
Babe: No. It’s not safe, it’s… very dangerous, be careful.

Now that I got that out of my system, yes, as long as you call ‘quote’
(as you are) you should be fine.

i would have written it this way

def AddCond(query, prefix, value, suffix)
return if value.blank?
" and #{query) #{prefix}#{Report.quote(value)}#{suffix}"
end


#3

Thanks for your answer.
Some corrections were necessary:

def AddCond(query, prefix, value, suffix)
return “” if value.blank?
" and #{query} #{Report.quote(prefix+value+suffix)}"
end

cheers