2007-01-22 14:43:50 +01:00
|
|
|
module ActiveRecord
|
|
|
|
module ConnectionAdapters # :nodoc:
|
|
|
|
module Quoting
|
|
|
|
# Quotes the column value to help prevent
|
|
|
|
# {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
|
|
|
|
def quote(value, column = nil)
|
2007-02-09 09:04:31 +01:00
|
|
|
# records are quoted as their primary key
|
|
|
|
return value.quoted_id if value.respond_to?(:quoted_id)
|
|
|
|
|
2007-01-22 14:43:50 +01:00
|
|
|
case value
|
2007-02-09 09:04:31 +01:00
|
|
|
when String, ActiveSupport::Multibyte::Chars
|
|
|
|
value = value.to_s
|
2007-01-22 14:43:50 +01:00
|
|
|
if column && column.type == :binary && column.class.respond_to?(:string_to_binary)
|
2007-12-21 08:48:59 +01:00
|
|
|
"#{quoted_string_prefix}'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode)
|
2007-02-09 09:04:31 +01:00
|
|
|
elsif column && [:integer, :float].include?(column.type)
|
|
|
|
value = column.type == :integer ? value.to_i : value.to_f
|
2007-01-22 14:43:50 +01:00
|
|
|
value.to_s
|
|
|
|
else
|
2007-12-21 08:48:59 +01:00
|
|
|
"#{quoted_string_prefix}'#{quote_string(value)}'" # ' (for ruby-mode)
|
2007-01-22 14:43:50 +01:00
|
|
|
end
|
2007-02-09 09:04:31 +01:00
|
|
|
when NilClass then "NULL"
|
|
|
|
when TrueClass then (column && column.type == :integer ? '1' : quoted_true)
|
|
|
|
when FalseClass then (column && column.type == :integer ? '0' : quoted_false)
|
|
|
|
when Float, Fixnum, Bignum then value.to_s
|
|
|
|
# BigDecimals need to be output in a non-normalized form and quoted.
|
|
|
|
when BigDecimal then value.to_s('F')
|
2007-12-21 08:48:59 +01:00
|
|
|
else
|
|
|
|
if value.acts_like?(:date) || value.acts_like?(:time)
|
|
|
|
"'#{quoted_date(value)}'"
|
|
|
|
else
|
|
|
|
"#{quoted_string_prefix}'#{quote_string(value.to_yaml)}'"
|
|
|
|
end
|
2007-01-22 14:43:50 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# Quotes a string, escaping any ' (single quote) and \ (backslash)
|
|
|
|
# characters.
|
|
|
|
def quote_string(s)
|
|
|
|
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
|
|
|
|
end
|
|
|
|
|
2007-12-21 08:48:59 +01:00
|
|
|
# Quotes the column name. Defaults to no quoting.
|
|
|
|
def quote_column_name(column_name)
|
|
|
|
column_name
|
|
|
|
end
|
|
|
|
|
|
|
|
# Quotes the table name. Defaults to column name quoting.
|
|
|
|
def quote_table_name(table_name)
|
|
|
|
quote_column_name(table_name)
|
2007-01-22 14:43:50 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def quoted_true
|
|
|
|
"'t'"
|
|
|
|
end
|
2007-12-21 08:48:59 +01:00
|
|
|
|
2007-01-22 14:43:50 +01:00
|
|
|
def quoted_false
|
|
|
|
"'f'"
|
|
|
|
end
|
2007-12-21 08:48:59 +01:00
|
|
|
|
2007-01-22 14:43:50 +01:00
|
|
|
def quoted_date(value)
|
2007-12-21 08:48:59 +01:00
|
|
|
value.to_s(:db)
|
|
|
|
end
|
|
|
|
|
|
|
|
def quoted_string_prefix
|
|
|
|
''
|
2007-01-22 14:43:50 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|