Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve sanitize_sql_like performance #44769

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions activerecord/lib/active_record/sanitization.rb
Expand Up @@ -107,8 +107,11 @@ def sanitize_sql_hash_for_assignment(attrs, table)
# sanitize_sql_like("snake_cased_string", "!")
# # => "snake!_cased!_string"
def sanitize_sql_like(string, escape_character = "\\")
pattern = Regexp.union(escape_character, "%", "_")
string.gsub(pattern) { |x| [escape_character, x].join }
if string.include?(escape_character) && escape_character != "%" && escape_character != "_"
string = string.gsub(escape_character, '\0\0')
end

string.gsub(/(?=[%_])/, escape_character)
end

# Accepts an array of conditions. The array has each value
Expand Down
5 changes: 5 additions & 0 deletions activerecord/test/cases/sanitize_test.rb
Expand Up @@ -75,6 +75,11 @@ def test_sanitize_sql_like_with_custom_escape_character
assert_equal "normal string 42", Binary.sanitize_sql_like("normal string 42", "!")
end

def test_sanitize_sql_like_with_wildcard_as_escape_character
assert_equal "1__000_%", Binary.sanitize_sql_like("1_000%", "_")
assert_equal "1%_000%%", Binary.sanitize_sql_like("1_000%", "%")
end

def test_sanitize_sql_like_example_use_case
searchable_post = Class.new(Post) do
def self.search_as_method(term)
Expand Down