Created
September 6, 2012 13:31
-
-
Save kaznum/3656283 to your computer and use it in GitHub Desktop.
SQL92 compatible LIKE escaping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have a pull request for this? I'd love to give this a 👍 for what it's worth.