Skip to content

Instantly share code, notes, and snippets.

@kaznum
Created September 6, 2012 13:31
Show Gist options
  • Save kaznum/3656283 to your computer and use it in GitHub Desktop.
Save kaznum/3656283 to your computer and use it in GitHub Desktop.
SQL92 compatible LIKE escaping
# SQL92 style "LIKE" escaped expression support
#
# load via initializer in Rails
#
# Arel supports the following expression
# where(Item.arel_table[:name].matches("%#{str}%")
# and str have to be escaped.
# The following code specify '!' as an ESCAPE character.
# The target characters to escape are /[%_!]/
# When these characters are escaped with proceeding "!", the following code escapes these character correctly.
# e.g. ...matches("%aa!%bb") matches "XXaa!%bb" but not fot "XXaa!YYbb"
# This code works with MySQL, PostgreSQL and SQLite3 at least.
#
module ArelExt
module Visitors
module ToSql
module InstanceMethods
def self.included(base)
base.class_eval do
alias_method_chain :visit_Arel_Nodes_Matches, :format_sql92
alias_method_chain :visit_Arel_Nodes_DoesNotMatch, :format_sql92
end
end
def visit_Arel_Nodes_Matches_with_format_sql92 o
visit_Arel_Nodes_Matches_without_format_sql92(o) + " ESCAPE '!'"
end
def visit_Arel_Nodes_DoesNotMatch_with_format_sql92 o
visit_Arel_Nodes_DoesNotMatch_without_format_sql92(o) + " ESCAPE '!'"
end
end
end
end
end
ActiveSupport.on_load(:active_record) do
Arel::Visitors::ToSql.send(:include, ArelExt::Visitors::ToSql::InstanceMethods)
Arel::Visitors::PostgreSQL.send(:include, ArelExt::Visitors::ToSql::InstanceMethods)
end
@avit
Copy link

avit commented Oct 9, 2013

Do you have a pull request for this? I'd love to give this a 👍 for what it's worth.

@avit
Copy link

avit commented Oct 9, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment