Having followed some tips on escaping apostrophes I am getting an unexpected combination of escape characters in the resulting sql statement. The following rails 4 active record statement is run against 5.5.42-MariaDB:
User.where(["surname LIKE ?", "%#{params[:search]}%"])
Where
params[:search] = "O'Keefe"
A .to_sql
generates
SELECT * FROM users WHERE surname LIKE '%O\\'Keefe%'
MySQL/MariaBD expects an apostrophe to be escaped as two single apostrophes ''
, or with a single backslash \'
so this results in a syntax error. I am looking for help to understand why two backslashes \\'
are appearing, and for a solution that will maintain protection against SQL injection.
UPDATE
After further investigation following suggestions below, it appears as though the console .to_sql
output SELECT * FROM users WHERE surname LIKE '%O\\'Keefe%'
is not what is passed onto MySQL. It failed for me 'cos I simply copied the statement into a mysql console to test execution. There is some black magic on route to the database that converts the double backslash \\'
into a valid mysql escape sequence.
So problem 1/2 solved
User.where(["surname LIKE ?", "%#{params[:search]}%"])
is valid syntax that correctly auto-escapes the user input string. But can anyone shed any light on the reason for the generation of the double backslash and how it is modified on its way to database execution?