Skip to content

Commit

Permalink
Document string behaviour ActiveRecord::Sanitization
Browse files Browse the repository at this point in the history
Without carefully reading examples or the source code it's not clear that
.sanitize_sql_for_conditions and .sanitize_sql_for_assignment methods won't
sanitize strings and will result in a no-op. This is an attempt to raise
awareness of this unexpected behaviour from a method aliased as `.sanitize_sql`.
  • Loading branch information
bernardoamc committed Apr 6, 2023
1 parent c18e8ad commit a9b9bb0
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions activerecord/lib/active_record/sanitization.rb
Expand Up @@ -5,8 +5,8 @@ module Sanitization
extend ActiveSupport::Concern

module ClassMethods
# Accepts an array or string of SQL conditions and sanitizes
# them into a valid SQL fragment for a WHERE clause.
# Accepts an array of SQL conditions and sanitizes them into a valid
# SQL fragment for a WHERE clause.
#
# sanitize_sql_for_conditions(["name=? and group_id=?", "foo'bar", 4])
# # => "name='foo''bar' and group_id=4"
Expand All @@ -17,6 +17,9 @@ module ClassMethods
# sanitize_sql_for_conditions(["name='%s' and group_id='%s'", "foo'bar", 4])
# # => "name='foo''bar' and group_id='4'"
#
# This method will NOT sanitize a SQL string since it won't contain
# any conditions in it and will return the string as is.
#
# sanitize_sql_for_conditions("name='foo''bar' and group_id='4'")
# # => "name='foo''bar' and group_id='4'"
#
Expand All @@ -37,8 +40,8 @@ def sanitize_sql_for_conditions(condition)
end
alias :sanitize_sql :sanitize_sql_for_conditions

# Accepts an array, hash, or string of SQL conditions and sanitizes
# them into a valid SQL fragment for a SET clause.
# Accepts an array or hash of SQL conditions and sanitizes them into
# a valid SQL fragment for a SET clause.
#
# sanitize_sql_for_assignment(["name=? and group_id=?", nil, 4])
# # => "name=NULL and group_id=4"
Expand All @@ -49,6 +52,9 @@ def sanitize_sql_for_conditions(condition)
# Post.sanitize_sql_for_assignment({ name: nil, group_id: 4 })
# # => "`posts`.`name` = NULL, `posts`.`group_id` = 4"
#
# This method will NOT sanitize a SQL string since it won't contain
# any conditions in it and will return the string as is.
#
# sanitize_sql_for_assignment("name=NULL and group_id='4'")
# # => "name=NULL and group_id='4'"
#
Expand Down

0 comments on commit a9b9bb0

Please sign in to comment.