sanitization.rb 8.0 KB
Newer Older
1
require "active_support/core_ext/regexp"
X
Xavier Noria 已提交
2

3 4 5 6 7
module ActiveRecord
  module Sanitization
    extend ActiveSupport::Concern

    module ClassMethods
8 9
      # Used to sanitize objects before they're used in an SQL SELECT statement.
      # Delegates to {connection.quote}[rdoc-ref:ConnectionAdapters::Quoting#quote].
10
      def sanitize(object) # :nodoc:
11 12
        connection.quote(object)
      end
13
      alias_method :quote_value, :sanitize
14 15 16

      protected

17
      # Accepts an array or string of SQL conditions and sanitizes
18
      # them into a valid SQL fragment for a WHERE clause.
19 20 21 22
      #
      #   sanitize_sql_for_conditions(["name=? and group_id=?", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id=4"
      #
23 24 25
      #   sanitize_sql_for_conditions(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
      #   # => "name='foo''bar' and group_id='4'"
      #
26 27 28 29 30
      #   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'"
31
      def sanitize_sql_for_conditions(condition)
32 33 34 35 36 37 38 39
        return nil if condition.blank?

        case condition
        when Array; sanitize_sql_array(condition)
        else        condition
        end
      end
      alias_method :sanitize_sql, :sanitize_sql_for_conditions
40
      alias_method :sanitize_conditions, :sanitize_sql
41 42 43

      # Accepts an array, hash, or string of SQL conditions and sanitizes
      # them into a valid SQL fragment for a SET clause.
44 45 46 47
      #
      #   sanitize_sql_for_assignment(["name=? and group_id=?", nil, 4])
      #   # => "name=NULL and group_id=4"
      #
48 49 50
      #   sanitize_sql_for_assignment(["name=:name and group_id=:group_id", name: nil, group_id: 4])
      #   # => "name=NULL and group_id=4"
      #
51 52 53 54 55
      #   Post.send(: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'"
56
      def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name)
57
        case assignments
58
        when Array; sanitize_sql_array(assignments)
59
        when Hash;  sanitize_sql_hash_for_assignment(assignments, default_table_name)
60
        else        assignments
61 62 63
        end
      end

64
      # Accepts an array, or string of SQL conditions and sanitizes
65
      # them into a valid SQL fragment for an ORDER clause.
66 67 68 69 70 71 72
      #
      #   sanitize_sql_for_order(["field(id, ?)", [1,3,2]])
      #   # => "field(id, 1,3,2)"
      #
      #   sanitize_sql_for_order("id ASC")
      #   # => "id ASC"
      def sanitize_sql_for_order(condition)
73
        if condition.is_a?(Array) && condition.first.to_s.include?("?")
74 75 76 77 78 79
          sanitize_sql_array(condition)
        else
          condition
        end
      end

80
      # Accepts a hash of SQL conditions and replaces those attributes
81 82
      # that correspond to a {#composed_of}[rdoc-ref:Aggregations::ClassMethods#composed_of]
      # relationship with their expanded aggregate attribute values.
83
      #
84
      # Given:
85 86 87 88 89 90
      #
      #   class Person < ActiveRecord::Base
      #     composed_of :address, class_name: "Address",
      #       mapping: [%w(address_street street), %w(address_city city)]
      #   end
      #
91
      # Then:
92 93 94
      #
      #   { address: Address.new("813 abc st.", "chicago") }
      #   # => { address_street: "813 abc st.", address_city: "chicago" }
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
      def expand_hash_conditions_for_aggregates(attrs)
        expanded_attrs = {}
        attrs.each do |attr, value|
          if aggregation = reflect_on_aggregation(attr.to_sym)
            mapping = aggregation.mapping
            mapping.each do |field_attr, aggregate_attr|
              if mapping.size == 1 && !value.respond_to?(aggregate_attr)
                expanded_attrs[field_attr] = value
              else
                expanded_attrs[field_attr] = value.send(aggregate_attr)
              end
            end
          else
            expanded_attrs[attr] = value
          end
        end
        expanded_attrs
      end

114
      # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
115 116 117
      #
      #   sanitize_sql_hash_for_assignment({ status: nil, group_id: 1 }, "posts")
      #   # => "`posts`.`status` = NULL, `posts`.`group_id` = 1"
118
      def sanitize_sql_hash_for_assignment(attrs, table)
119
        c = connection
120
        attrs.map do |attr, value|
121
          value = type_for_attribute(attr.to_s).serialize(value)
122
          "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}"
123
        end.join(", ")
124 125
      end

A
Akshay Vishnoi 已提交
126
      # Sanitizes a +string+ so that it is safe to use within an SQL
127 128 129 130 131 132 133 134 135 136 137 138 139
      # LIKE statement. This method uses +escape_character+ to escape all occurrences of "\", "_" and "%".
      #
      #   sanitize_sql_like("100%")
      #   # => "100\\%"
      #
      #   sanitize_sql_like("snake_cased_string")
      #   # => "snake\\_cased\\_string"
      #
      #   sanitize_sql_like("100%", "!")
      #   # => "100!%"
      #
      #   sanitize_sql_like("snake_cased_string", "!")
      #   # => "snake!_cased!_string"
140
      def sanitize_sql_like(string, escape_character = "\\")
141 142
        pattern = Regexp.union(escape_character, "%", "_")
        string.gsub(pattern) { |x| [escape_character, x].join }
143 144
      end

145 146
      # Accepts an array of conditions. The array has each value
      # sanitized and interpolated into the SQL statement.
147 148 149 150
      #
      #   sanitize_sql_array(["name=? and group_id=?", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id=4"
      #
151 152 153
      #   sanitize_sql_array(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
      #   # => "name='foo''bar' and group_id=4"
      #
154 155
      #   sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4])
      #   # => "name='foo''bar' and group_id='4'"
156 157
      def sanitize_sql_array(ary)
        statement, *values = ary
158
        if values.first.is_a?(Hash) && /:\w+/.match?(statement)
159
          replace_named_bind_variables(statement, values.first)
160
        elsif statement.include?("?")
161 162 163 164 165 166 167 168
          replace_bind_variables(statement, values)
        elsif statement.blank?
          statement
        else
          statement % values.collect { |value| connection.quote_string(value.to_s) }
        end
      end

169
      def replace_bind_variables(statement, values) # :nodoc:
170
        raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size)
171 172
        bound = values.dup
        c = connection
173
        statement.gsub(/\?/) do
174 175 176 177
          replace_bind_variable(bound.shift, c)
        end
      end

178
      def replace_bind_variable(value, c = connection) # :nodoc:
179 180 181 182 183
        if ActiveRecord::Relation === value
          value.to_sql
        else
          quote_bound_value(value, c)
        end
184 185
      end

186
      def replace_named_bind_variables(statement, bind_vars) # :nodoc:
187
        statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match|
188
          if $1 == ":" # skip postgresql casts
189
            match # return the whole match
190
          elsif bind_vars.include?(match = $2.to_sym)
191
            replace_bind_variable(bind_vars[match])
192 193 194 195 196 197
          else
            raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
          end
        end
      end

198
      def quote_bound_value(value, c = connection) # :nodoc:
199
        if value.respond_to?(:map) && !value.acts_like?(:string)
200 201 202
          if value.respond_to?(:empty?) && value.empty?
            c.quote(nil)
          else
203
            value.map { |v| c.quote(v) }.join(",")
204 205
          end
        else
206
          c.quote(value)
207 208 209
        end
      end

210
      def raise_if_bind_arity_mismatch(statement, expected, provided) # :nodoc:
211 212 213 214 215 216 217
        unless expected == provided
          raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
        end
      end
    end

    # TODO: Deprecate this
218
    def quoted_id # :nodoc:
219
      self.class.quote_value(@attributes[self.class.primary_key].value_for_database)
220 221 222
    end
  end
end