escape() not actually escaping backslashes

Issue #26 invalid
Anonymous created an issue

ActiveRecord is calling into the PGconn instance for the method escape() to escape strings. This method does not appear to be escaping backslashes at all, which causes syntax errors in the SQL, if the backslash occurs at the end of a string:



conn = ActiveRecord::Base.connection.instance_variable_get("@Luis Santana")
=> #<PGconn:0x7f797772d268>
conn.escape("Foo \")
=> "Foo \"


I noticed this in 0.8.0, and just upgraded to 0.9.0 and found the same problem.

Comments (5)

  1. Michael Granger repo owner
    • changed status to open

    Huh, strange. There must be something different in your environment, then, because when I do the same thing outside of ActiveRecord:

    irb(main):001:0> conn = PGconn.connect( :dbname => 'test' )
    => #<PGconn:0x101037670>
    irb(main):002:0> conn.escape("Foo \\")
    => "Foo \\\\"
    irb(main):003:0> PGconn::VERSION
    => "0.9.0"

    Can you do me a favor and try it using a PGconn object you've created yourself instead of one fetched from ActiveRecord? Also helpful would be the version of ActiveRecord and ActiveSupport you're using, which version of Ruby, and which version of PostgreSQL.

    Thanks for your report!

  2. Anonymous

    My compatriot here figured it out. We have our Postgres server running with the option "standard_conforming_strings = on". When I turn it off, the lib does what's expected. Turn it on, it doesn't.

  3. Anonymous

    Okay, also figured out the problem with ActiveRecord's PostgresqlAdapter, FWIW...

    The AR adapter is checking to see if standard_conforming_strings are supported, and if they're supported, it's prepending E to any quoted string results, because that should be a consistent way to pass strings to Postgres regardless of whether s_c_s is on or off. However, since the pg gem (perhaps libpg underneath?) is already taking that into account, with s_c_s is on, AR is sending E''-type strings, but then the call to quote is NOT actually escaping the backslashes. AR wasn't/isn't prepared for the pg gem to be "intelligent" about the s_c_s option. As a result, with s_c_s on, AR sends broken queries like SELECT E'foo \';

    This probably is not really an issue with the pg gem, per se, just a mismatch of expected behaviors between the two layers. I'll go hit up the Rails bug tracker next... :)

  4. Log in to comment