diff options
author | Sean McGivern <sean@mcgivern.me.uk> | 2017-06-29 15:20:47 +0000 |
---|---|---|
committer | Sean McGivern <sean@mcgivern.me.uk> | 2017-06-29 15:20:47 +0000 |
commit | 31c21d50fcd64bf9a2fde0e2358a416237334be2 (patch) | |
tree | feeb5b74fde011168d44a8af6a52a29691811ddb /lib | |
parent | 0b704d4ece1fd42b324a85befaace9f7c5345f3d (diff) | |
parent | af1f6844c98bfb4adda1c20dc75b808f031a4256 (diff) | |
download | gitlab-ce-31c21d50fcd64bf9a2fde0e2358a416237334be2.tar.gz |
Merge branch 'sha-attributes-for-postgresql-and-mysql' into 'master'
Added code for defining SHA attributes
See merge request !12555
Diffstat (limited to 'lib')
-rw-r--r-- | lib/gitlab/database/sha_attribute.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/gitlab/database/sha_attribute.rb b/lib/gitlab/database/sha_attribute.rb new file mode 100644 index 00000000000..d9400e04b83 --- /dev/null +++ b/lib/gitlab/database/sha_attribute.rb @@ -0,0 +1,34 @@ +module Gitlab + module Database + BINARY_TYPE = if Gitlab::Database.postgresql? + # PostgreSQL defines its own class with slightly different + # behaviour from the default Binary type. + ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea + else + ActiveRecord::Type::Binary + end + + # Class for casting binary data to hexadecimal SHA1 hashes (and vice-versa). + # + # Using ShaAttribute allows you to store SHA1 values as binary while still + # using them as if they were stored as string values. This gives you the + # ease of use of string values, but without the storage overhead. + class ShaAttribute < BINARY_TYPE + PACK_FORMAT = 'H*'.freeze + + # Casts binary data to a SHA1 in hexadecimal. + def type_cast_from_database(value) + value = super + + value ? value.unpack(PACK_FORMAT)[0] : nil + end + + # Casts a SHA1 in hexadecimal to the proper binary format. + def type_cast_for_database(value) + arg = value ? [value].pack(PACK_FORMAT) : nil + + super(arg) + end + end + end +end |