Skip to content

Commit

Permalink
Use StringScanner to parse Hstore payloads
Browse files Browse the repository at this point in the history
  • Loading branch information
pixeltrix authored and byroot committed Apr 13, 2021
1 parent 9ef7f40 commit 98bf64b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 11 deletions.
@@ -1,32 +1,71 @@
# frozen_string_literal: true

require "strscan"

module ActiveRecord
module ConnectionAdapters
module PostgreSQL
module OID # :nodoc:
class Hstore < Type::Value # :nodoc:
ERROR = "Invalid Hstore document: %s"

include ActiveModel::Type::Helpers::Mutable

def type
:hstore
end

def deserialize(value)
if value.is_a?(::String)
hash = {}
value.scan(HstorePair) do |key, value|
key.gsub!('\"', '"')
key.gsub!('\\\\', '\\')
return value unless value.is_a?(::String)

value&.gsub!('\"', '"')
value&.gsub!('\\\\', '\\')
scanner = StringScanner.new(value)
hash = {}

hash[key] = value
until scanner.eos?
unless scanner.skip(/"/)
raise(ArgumentError, ERROR % scanner.string.inspect)
end

unless key = scanner.scan_until(/(?<!\\)(?=")/)
raise(ArgumentError, ERROR % scanner.string.inspect)
end

unless scanner.skip(/"=>?/)
raise(ArgumentError, ERROR % scanner.string.inspect)
end

if scanner.scan(/NULL/)
value = nil
else
unless scanner.skip(/"/)
raise(ArgumentError, ERROR % scanner.string.inspect)
end

unless value = scanner.scan_until(/(?<!\\)(?=")/)
raise(ArgumentError, ERROR % scanner.string.inspect)
end

unless scanner.skip(/"/)
raise(ArgumentError, ERROR % scanner.string.inspect)
end
end

key.gsub!('\"', '"')
key.gsub!('\\\\', '\\')

if value
value.gsub!('\"', '"')
value.gsub!('\\\\', '\\')
end

hash[key] = value

unless scanner.skip(/, /) || scanner.eos?
raise(ArgumentError, ERROR % scanner.string.inspect)
end
hash
else
value
end

hash
end

def serialize(value)
Expand Down
1 change: 1 addition & 0 deletions activerecord/test/cases/adapters/postgresql/hstore_test.rb
Expand Up @@ -291,6 +291,7 @@ def test_whitespace

def test_backslash
assert_cycle('a\\b' => 'b\\ar', '1"foo' => "2")
assert_cycle('a\\"' => 'b\\ar', '1"foo' => "2")
end

def test_comma
Expand Down

0 comments on commit 98bf64b

Please sign in to comment.