diff options
author | Sean Griffin <sean@thoughtbot.com> | 2014-10-31 11:23:24 -0600 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2014-10-31 12:15:36 -0600 |
commit | e62fff40edde10bd04bbb91ce242f4a7f7ea64a8 (patch) | |
tree | f984582034b23691663a54fa978d5cbf4d8e403e /activerecord/lib/active_record/type/integer.rb | |
parent | 9b9f0197b7e645ae5b05a5581ba82f32f0971183 (diff) | |
download | rails-e62fff40edde10bd04bbb91ce242f4a7f7ea64a8.tar.gz rails-e62fff40edde10bd04bbb91ce242f4a7f7ea64a8.tar.bz2 rails-e62fff40edde10bd04bbb91ce242f4a7f7ea64a8.zip |
Treat strings greater than int max value as out of range
Sufficiently large integers cause `find` and `find_by` to raise
`StatementInvalid` instead of `RecordNotFound` or just returning `nil`.
Given that we can't cast to `nil` for `Integer` like we would with junk
data for other types, we raise a `RangeError` instead, and rescue in
places where it would be highly unexpected to get an exception from
casting.
Fixes #17380
Diffstat (limited to 'activerecord/lib/active_record/type/integer.rb')
-rw-r--r-- | activerecord/lib/active_record/type/integer.rb | 21 |
1 files changed, 20 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index 08477d1303..2b0f0b2734 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -15,9 +15,28 @@ module ActiveRecord case value when true then 1 when false then 0 - else value.to_i rescue nil + else + result = value.to_i rescue nil + ensure_below_max(result) if result + result end end + + def ensure_below_max(value) + if value > max_value + raise RangeError, "#{value} is too large for #{self.class} with limit #{limit || 4}" + end + end + + def max_value + @max_value = determine_max_value unless defined?(@max_value) + @max_value + end + + def determine_max_value + limit = self.limit || 4 + 2 << (limit * 8 - 1) # 8 bits per byte with one bit for sign + end end end end |