Skip to content

Commit

Permalink
Collapse PG default extractoin of most types to single regex
Browse files Browse the repository at this point in the history
For any type that is represented as a string and then type cast, we do
not need separate regular expressions for the various types. No function
will match this regex. User defined types *should* match this, so that
the type object can decide what to do with the value.
  • Loading branch information
sgrif committed Jun 4, 2014
1 parent 0329d59 commit 405fd22
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -511,58 +511,16 @@ def extract_value_from_default(oid, default) # :nodoc:
# makes this method very very slow.
return default unless default

# TODO: The default extraction is related to the cast-type.
# we should probably make a type_map lookup and cast the default-
# expression accordingly
if oid.type == :enum && default =~ /\A'(.*)'::/
return $1
end

case default
when /\A'(.*)'::(num|date|tstz|ts|int4|int8)range\z/m
$1
# Quoted types
when /\A[\(B]?'(.*)'::/m
$1.gsub(/''/, "'")
# Boolean types
when 'true', 'false'
default
# Numeric types
when /\A\(?(-?\d+(\.\d*)?\)?(::bigint)?)\z/
$1
# Character types
when /\A\(?'(.*)'::.*\b(?:character varying|bpchar|text)\z/m
$1.gsub(/''/, "'")
# Binary data types
when /\A'(.*)'::bytea\z/m
$1
# Date/time types
when /\A'(.+)'::(?:time(?:stamp)? with(?:out)? time zone|date)\z/
$1
when /\A'(.*)'::interval\z/
$1
# Boolean type
when 'true'
true
when 'false'
false
# Geometric types
when /\A'(.*)'::(?:point|line|lseg|box|"?path"?|polygon|circle)\z/
$1
# Network address types
when /\A'(.*)'::(?:cidr|inet|macaddr)\z/
$1
# Bit string types
when /\AB'(.*)'::"?bit(?: varying)?"?\z/
$1
# XML type
when /\A'(.*)'::xml\z/m
$1
# Arrays
when /\A'(.*)'::"?\D+"?\[\]\z/
$1
# Hstore
when /\A'(.*)'::hstore\z/
$1
# JSON
when /\A'(.*)'::json\z/
$1
when /\A'(.*)'::money\z/
$1
# Object identifier types
when /\A-?\d+\z/
$1
Expand Down
5 changes: 5 additions & 0 deletions activerecord/test/cases/defaults_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,11 @@ def test_text_defaults_after_updating_column_default
assert_equal "some text", Default.new.text_col, "Default of text column was not correctly parse after updating default using '::text' since postgreSQL will add parens to the default in db"
end

def test_default_containing_quote_and_colons
@connection.execute "ALTER TABLE defaults ALTER COLUMN string_col SET DEFAULT 'foo''::bar'"
assert_equal "foo'::bar", Default.new.string_col
end

teardown do
@connection.schema_search_path = @old_search_path
Default.reset_column_information
Expand Down

0 comments on commit 405fd22

Please sign in to comment.