Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Backslashes doesn't work in LIKE queries with PostgreSQL adapter

#1309

For example:

class Resource < ActiveRecord::Base; end Resource.create(:path => "foo\bar\baz") Resource.find(:all, :conditions => [ "resources.path like ?", "%ar\ba%" ] ).each { |rs| puts rs.path }

This does not return any objects. It works with the SQLite3 adapter.

Exact queries does actually work ("resources.path = ?", ...). It is also possible to get the above working by escaping the backslash one more time:

Resource.find(:all, :conditions => [ "resources.path like ?", "%ar\\ba%" ] ).each { |rs| puts rs.path }

PostgreSQL version: 8.3.3. ROR version: 2.1.1

Reported by Lars Christensen · October 31st, 2008 @ 12:18 PM

State: invalid
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Lars Christensen
    Lars Christensen

    I have realised that LIKE clauses require special escaping of %, _, and . PostgreSQL defaults to having backslash as the escape operator, while SQLite default to NOT having an escape operator. Furthermore, PostgreSQL requires escaping of backslashes in strings in general, while SQLite does not.

    To select strings containing "%_" would in SQLite be:

    select ... where name like '\%_\' ESCAPE ''

    and in PostgreSQL

    select ... where name like E'\%\_\\' ESCAPE '\';

    A portable way seems to be:

    filter.gsub!(/[\%_]/, "\\\0") Record.find(:all, :conditions => [ "name like ? escape ?", "%#{filter}%", "\" ]

    November 5th, 2008 @ 08:28 AM

  2. Pratik
    Pratik
    • State changed from new to incomplete
    • Assigned user set to Tarmo Tänav

    You should probably try to submit a failing test.

    Thanks.

    March 12th, 2009 @ 04:05 PM

  3. CancelProfileIsBroken
    CancelProfileIsBroken
    • Tag changed from 2.1.1, :conditions, postgresql, sql to 2.1.1, :conditions, bugmash, postgresql, sql

    August 5th, 2009 @ 03:30 PM

  4. Elise Huard
    Elise Huard

    -1 tested with master on postgresql 8.3.5 with ruby1.8.6 and unable to reproduce

    >> u = User.create(:name => 'tra/la/la')
    => #<User id: 3, name: "tra/la/la", created_at: "2009-08-09 22:19:01", updated_at: "2009-08-09 22:19:01">
    >> User.find(:all,:conditions => ["users.name like ?","%tra/la%"])
    => [#<User id: 3, name: "tra/la/la", created_at: "2009-08-09 22:19:01", updated_at: "2009-08-09 22:19:01">]
    

    August 9th, 2009 @ 11:22 PM

  5. Rizwan Reza
    Rizwan Reza
    • State changed from incomplete to invalid
    • Tag changed from 2.1.1, :conditions, bugmash, postgresql, sql to 2.1.1, :conditions, postgresql, sql
    • Assigned user cleared.

    January 20th, 2010 @ 11:30 AM