rubysequel

single quote escape inside double quotes using sequel fetch function in ruby


using raw SQL when I use the IN statement inside a query using sequel's fetch function, I can't escape a single quote by writing where stuff IN ...

@values='stuff1\'','stuff2\''

db.fetch("query...where IN (?)", "#{@values}")

outputs query...where stuff IN ('stuff1'',''stuff2') instead of ('stuff1','stuff2')

Quite frustrating that I'd probably have to write a Sequel equivalent for the raw query or use a different ORM just because of this escape issue. Any thoughts?


Solution

  • If I understand the Sequel documentation correctly, using String#lit or Sequel.lit should turn a Ruby string into a literal string and bypass the automatic escaping mechanism; therefore, this should work (untested):

    @values='stuff1\'','stuff2\''.lit
    
    db.fetch("query...where IN (?)", "#{@values}")
    

    The usual caveats when working with raw SQL strings (SQL injection attacks, inefficient SQL due to forced re-parsing of statements etc.) apply :-)