lundi 9 janvier 2017

rails mysql regex input not getting sanitized properly

I am doing the following on a rails 3 app

def test(str)
    User.where("name REGEXP ?",str).last
end

Using the format above, rails generally handles sanitizing the input. However it fails on few cases.

If I use

str = "hi\\"

I get this error:-

ActiveRecord::StatementInvalid: Mysql2::Error: Got error 'trailing backslash (\)' from regexp: SELECT  `users`.* FROM `users`  WHERE (name REGEXP 'hi\\') ORDER BY `users`.`id` DESC LIMIT 1

If I use

str="hi("

I get this error

ActiveRecord::StatementInvalid: Mysql2::Error: Got error 'parentheses not balanced' from regexp: SELECT  `users`.* FROM `users`  WHERE (name REGEXP 'hi(') ORDER BY `users`.`id` DESC LIMIT 1

For cases like str = "hi)" it works:-

Is there clean rails way of handling the input before it gets executed in regex sql?

Aucun commentaire:

Enregistrer un commentaire