Module: ActiveRecord::Sanitization::ClassMethods

Defined in:
lib/active_record/sanitization.rb

Instance Method Summary collapse

Instance Method Details

#disallow_raw_sql!(args, permit: connection.column_name_matcher) ⇒ Object

:nodoc:



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/active_record/sanitization.rb', line 138

def disallow_raw_sql!(args, permit: connection.column_name_matcher) # :nodoc:
  unexpected = nil
  args.each do |arg|
    next if arg.is_a?(Symbol) || Arel.arel_node?(arg) || permit.match?(arg.to_s.strip)
    (unexpected ||= []) << arg
  end

  if unexpected
    raise(ActiveRecord::UnknownAttributeReference,
      "Dangerous query method (method whose arguments are used as raw " \
      "SQL) called with non-attribute argument(s): " \
      "#{unexpected.map(&:inspect).join(", ")}." \
      "This method should not be called with user-provided values, such as request " \
      "parameters or model attributes. Known-safe values can be passed " \
      "by wrapping them in Arel.sql()."
    )
  end
end

#sanitize_sql_array(ary) ⇒ Object

Accepts an array of conditions. The array has each value sanitized and interpolated into the SQL statement.

sanitize_sql_array(["name=? and group_id=?", "foo'bar", 4])
# => "name='foo''bar' and group_id=4"

sanitize_sql_array(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
# => "name='foo''bar' and group_id=4"

sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4])
# => "name='foo''bar' and group_id='4'"


125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/active_record/sanitization.rb', line 125

def sanitize_sql_array(ary)
  statement, *values = ary
  if values.first.is_a?(Hash) && /:\w+/.match?(statement)
    replace_named_bind_variables(statement, values.first)
  elsif statement.include?("?")
    replace_bind_variables(statement, values)
  elsif statement.blank?
    statement
  else
    statement % values.collect { |value| connection.quote_string(value.to_s) }
  end
end

#sanitize_sql_for_assignment(assignments, default_table_name = table_name) ⇒ Object

Accepts an array, hash, or string 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"

sanitize_sql_for_assignment(["name=:name and group_id=:group_id", name: nil, group_id: 4])
# => "name=NULL and group_id=4"

Post.sanitize_sql_for_assignment({ name: nil, group_id: 4 })
# => "`posts`.`name` = NULL, `posts`.`group_id` = 4"

sanitize_sql_for_assignment("name=NULL and group_id='4'")
# => "name=NULL and group_id='4'"


46
47
48
49
50
51
52
# File 'lib/active_record/sanitization.rb', line 46

def sanitize_sql_for_assignment(assignments, default_table_name = table_name)
  case assignments
  when Array; sanitize_sql_array(assignments)
  when Hash;  sanitize_sql_hash_for_assignment(assignments, default_table_name)
  else        assignments
  end
end

#sanitize_sql_for_conditions(condition) ⇒ Object Also known as: sanitize_sql

Accepts an array or string 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"

sanitize_sql_for_conditions(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
# => "name='foo''bar' and group_id='4'"

sanitize_sql_for_conditions(["name='%s' and group_id='%s'", "foo'bar", 4])
# => "name='foo''bar' and group_id='4'"

sanitize_sql_for_conditions("name='foo''bar' and group_id='4'")
# => "name='foo''bar' and group_id='4'"


22
23
24
25
26
27
28
29
# File 'lib/active_record/sanitization.rb', line 22

def sanitize_sql_for_conditions(condition)
  return nil if condition.blank?

  case condition
  when Array; sanitize_sql_array(condition)
  else        condition
  end
end

#sanitize_sql_for_order(condition) ⇒ Object

Accepts an array, or string of SQL conditions and sanitizes them into a valid SQL fragment for an ORDER clause.

sanitize_sql_for_order([Arel.sql("field(id, ?)"), [1,3,2]])
# => "field(id, 1,3,2)"

sanitize_sql_for_order("id ASC")
# => "id ASC"


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/active_record/sanitization.rb', line 62

def sanitize_sql_for_order(condition)
  if condition.is_a?(Array) && condition.first.to_s.include?("?")
    disallow_raw_sql!(
      [condition.first],
      permit: connection.column_name_with_order_matcher
    )

    # Ensure we aren't dealing with a subclass of String that might
    # override methods we use (e.g. Arel::Nodes::SqlLiteral).
    if condition.first.kind_of?(String) && !condition.first.instance_of?(String)
      condition = [String.new(condition.first), *condition[1..-1]]
    end

    Arel.sql(sanitize_sql_array(condition))
  else
    condition
  end
end

#sanitize_sql_hash_for_assignment(attrs, table) ⇒ Object

Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.

sanitize_sql_hash_for_assignment({ status: nil, group_id: 1 }, "posts")
# => "`posts`.`status` = NULL, `posts`.`group_id` = 1"


85
86
87
88
89
90
91
92
# File 'lib/active_record/sanitization.rb', line 85

def sanitize_sql_hash_for_assignment(attrs, table)
  c = connection
  attrs.map do |attr, value|
    type = type_for_attribute(attr)
    value = type.serialize(type.cast(value))
    "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}"
  end.join(", ")
end

#sanitize_sql_like(string, escape_character = "\\") ⇒ Object

Sanitizes a string so that it is safe to use within an SQL LIKE statement. This method uses escape_character to escape all occurrences of itself, “_” and “%”.

sanitize_sql_like("100% true!")
# => "100\\% true!"

sanitize_sql_like("snake_cased_string")
# => "snake\\_cased\\_string"

sanitize_sql_like("100% true!", "!")
# => "100!% true!!"

sanitize_sql_like("snake_cased_string", "!")
# => "snake!_cased!_string"


109
110
111
112
# File 'lib/active_record/sanitization.rb', line 109

def sanitize_sql_like(string, escape_character = "\\")
  pattern = Regexp.union(escape_character, "%", "_")
  string.gsub(pattern) { |x| [escape_character, x].join }
end