quoting.rb 6.2 KB
Newer Older
1
require "active_support/core_ext/big_decimal/conversions"
2
require "active_support/multibyte/chars"
J
Jeremy Kemper 已提交
3

4 5 6
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module Quoting
7 8
      # Quotes the column value to help prevent
      # {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
9
      def quote(value)
10 11 12
        # records are quoted as their primary key
        return value.quoted_id if value.respond_to?(:quoted_id)

13
        _quote(value)
14 15
      end

16 17 18
      # Cast a +value+ to a type that the database understands. For example,
      # SQLite does not understand dates, so this method will convert a Date
      # to a String.
19
      def type_cast(value, column = nil)
20 21 22
        if value.respond_to?(:quoted_id) && value.respond_to?(:id)
          return value.id
        end
23

24
        if column
25
          value = type_cast_from_column(column, value)
26 27
        end

28 29 30 31
        _type_cast(value)
      rescue TypeError
        to_type = column ? " to #{column.type}" : ""
        raise TypeError, "can't cast #{value.class}#{to_type}"
32 33
      end

34 35 36
      # If you are having to call this function, you are likely doing something
      # wrong. The column does not have sufficient type information if the user
      # provided a custom type on the class level either explicitly (via
37 38 39
      # Attributes::ClassMethods#attribute) or implicitly (via
      # AttributeMethods::Serialization::ClassMethods#serialize, +time_zone_aware_attributes+).
      # In almost all cases, the sql type should only be used to change quoting behavior, when the primitive to
40 41 42 43 44 45
      # represent the type doesn't sufficiently reflect the differences
      # (varchar vs binary) for example. The type used to get this primitive
      # should have been provided before reaching the connection adapter.
      def type_cast_from_column(column, value) # :nodoc:
        if column
          type = lookup_cast_type_from_column(column)
46
          type.serialize(value)
47 48 49 50 51
        else
          value
        end
      end

52
      # See docs for #type_cast_from_column
53 54 55 56
      def lookup_cast_type_from_column(column) # :nodoc:
        lookup_cast_type(column.sql_type)
      end

S
Sean Griffin 已提交
57 58 59 60 61 62 63 64 65 66 67
      def fetch_type_metadata(sql_type)
        cast_type = lookup_cast_type(sql_type)
        SqlTypeMetadata.new(
          sql_type: sql_type,
          type: cast_type.type,
          limit: cast_type.limit,
          precision: cast_type.precision,
          scale: cast_type.scale,
        )
      end

68 69
      # Quotes a string, escaping any ' (single quote) and \ (backslash)
      # characters.
70
      def quote_string(s)
B
brainopia 已提交
71
        s.gsub('\\'.freeze, '\&\&'.freeze).gsub("'".freeze, "''".freeze) # ' (for ruby-mode)
72 73
      end

74 75
      # Quotes the column name. Defaults to no quoting.
      def quote_column_name(column_name)
76
        column_name.to_s
77 78 79 80 81
      end

      # Quotes the table name. Defaults to column name quoting.
      def quote_table_name(table_name)
        quote_column_name(table_name)
82 83
      end

84 85 86
      # Override to return the quoted table name for assignment. Defaults to
      # table quoting.
      #
87
      # This works for mysql2 where table.column can be used to
88 89
      # resolve ambiguity.
      #
90
      # We override this in the sqlite3 and postgresql adapters to use only
91 92 93 94 95
      # the column name (as per syntax requirements).
      def quote_table_name_for_assignment(table, attr)
        quote_table_name("#{table}.#{attr}")
      end

96 97 98 99 100 101 102
      def quote_default_expression(value, column) # :nodoc:
        if value.is_a?(Proc)
          value.call
        else
          value = lookup_cast_type(column.sql_type).serialize(value)
          quote(value)
        end
103 104
      end

105
      def quoted_true
106
        "'t'".freeze
107
      end
108

109
      def unquoted_true
110
        "t".freeze
111 112
      end

113
      def quoted_false
114
        "'f'".freeze
115
      end
116

117
      def unquoted_false
118
        "f".freeze
119 120
      end

121 122
      # Quote date/time values for use in SQL input. Includes microseconds
      # if the value is a Time responding to usec.
123
      def quoted_date(value)
124 125
        if value.acts_like?(:time)
          zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
J
Jon Leighton 已提交
126 127 128 129 130 131

          if value.respond_to?(zone_conversion_method)
            value = value.send(zone_conversion_method)
          end
        end

132 133 134 135 136 137
        result = value.to_s(:db)
        if value.respond_to?(:usec) && value.usec > 0
          "#{result}.#{sprintf("%06d", value.usec)}"
        else
          result
        end
138
      end
139

140
      def quoted_time(value) # :nodoc:
141
        quoted_date(value).sub(/\A2000-01-01 /, "")
142 143
      end

144 145 146 147
      def quoted_binary(value) # :nodoc:
        "'#{quote_string(value.to_s)}'"
      end

148 149
      private

150 151
        def type_casted_binds(binds)
          binds.map { |attr| type_cast(attr.value_for_database) }
152 153
        end

154 155 156 157 158 159
        def types_which_need_no_typecasting
          [nil, Numeric, String]
        end

        def _quote(value)
          case value
160
          when String, ActiveSupport::Multibyte::Chars
161 162 163 164 165 166 167
            "'#{quote_string(value.to_s)}'"
          when true       then quoted_true
          when false      then quoted_false
          when nil        then "NULL"
          # BigDecimals need to be put in a non-normalized form and quoted.
          when BigDecimal then value.to_s("F")
          when Numeric, ActiveSupport::Duration then value.to_s
168
          when Type::Binary::Data then quoted_binary(value)
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
          when Type::Time::Value then "'#{quoted_time(value)}'"
          when Date, Time then "'#{quoted_date(value)}'"
          when Symbol     then "'#{quote_string(value.to_s)}'"
          when Class      then "'#{value}'"
          else raise TypeError, "can't quote #{value.class.name}"
          end
        end

        def _type_cast(value)
          case value
          when Symbol, ActiveSupport::Multibyte::Chars, Type::Binary::Data
            value.to_s
          when true       then unquoted_true
          when false      then unquoted_false
          # BigDecimals need to be put in a non-normalized form and quoted.
          when BigDecimal then value.to_s("F")
          when Type::Time::Value then quoted_time(value)
          when Date, Time then quoted_date(value)
          when *types_which_need_no_typecasting
            value
          else raise TypeError
          end
191
        end
192 193
    end
  end
194
end