sanitization.rb 7.0 KB
Newer Older
1 2 3 4 5
module ActiveRecord
  module Sanitization
    extend ActiveSupport::Concern

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

      protected

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

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

56
      # Accepts a hash of SQL conditions and replaces those attributes
57 58
      # that correspond to a {#composed_of}[rdoc-ref:Aggregations::ClassMethods#composed_of]
      # relationship with their expanded aggregate attribute values.
59
      #
60
      # Given:
61 62 63 64 65 66
      #
      #   class Person < ActiveRecord::Base
      #     composed_of :address, class_name: "Address",
      #       mapping: [%w(address_street street), %w(address_city city)]
      #   end
      #
67
      # Then:
68 69 70
      #
      #   { address: Address.new("813 abc st.", "chicago") }
      #   # => { address_street: "813 abc st.", address_city: "chicago" }
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      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

90
      # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
91 92 93
      #
      #   sanitize_sql_hash_for_assignment({ status: nil, group_id: 1 }, "posts")
      #   # => "`posts`.`status` = NULL, `posts`.`group_id` = 1"
94
      def sanitize_sql_hash_for_assignment(attrs, table)
95
        c = connection
96
        attrs.map do |attr, value|
97
          value = type_for_attribute(attr.to_s).serialize(value)
98
          "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}"
99 100 101
        end.join(', ')
      end

A
Akshay Vishnoi 已提交
102
      # Sanitizes a +string+ so that it is safe to use within an SQL
103 104 105 106 107 108 109 110 111 112 113 114 115
      # 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"
116
      def sanitize_sql_like(string, escape_character = "\\")
117 118
        pattern = Regexp.union(escape_character, "%", "_")
        string.gsub(pattern) { |x| [escape_character, x].join }
119 120
      end

121 122
      # Accepts an array of conditions. The array has each value
      # sanitized and interpolated into the SQL statement.
123 124 125 126 127 128
      #
      #   sanitize_sql_array(["name=? and group_id=?", "foo'bar", 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'"
129 130 131 132 133 134 135 136 137 138 139 140 141
      def sanitize_sql_array(ary)
        statement, *values = ary
        if values.first.is_a?(Hash) && statement =~ /:\w+/
          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

142
      def replace_bind_variables(statement, values) # :nodoc:
143 144 145
        raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
        bound = values.dup
        c = connection
146
        statement.gsub(/\?/) do
147 148 149 150
          replace_bind_variable(bound.shift, c)
        end
      end

151
      def replace_bind_variable(value, c = connection) # :nodoc:
152 153 154 155 156
        if ActiveRecord::Relation === value
          value.to_sql
        else
          quote_bound_value(value, c)
        end
157 158
      end

159
      def replace_named_bind_variables(statement, bind_vars) # :nodoc:
160
        statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match|
161
          if $1 == ':' # skip postgresql casts
162
            match # return the whole match
163
          elsif bind_vars.include?(match = $2.to_sym)
164
            replace_bind_variable(bind_vars[match])
165 166 167 168 169 170
          else
            raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
          end
        end
      end

171
      def quote_bound_value(value, c = connection) # :nodoc:
172
        if value.respond_to?(:map) && !value.acts_like?(:string)
173 174 175 176 177 178
          if value.respond_to?(:empty?) && value.empty?
            c.quote(nil)
          else
            value.map { |v| c.quote(v) }.join(',')
          end
        else
179
          c.quote(value)
180 181 182
        end
      end

183
      def raise_if_bind_arity_mismatch(statement, expected, provided) # :nodoc:
184 185 186 187 188 189 190
        unless expected == provided
          raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
        end
      end
    end

    # TODO: Deprecate this
191
    def quoted_id
192
      self.class.quote_value(@attributes[self.class.primary_key].value_for_database)
193 194 195
    end
  end
end