summaryrefslogtreecommitdiff
path: root/lib/gitlab/database
diff options
context:
space:
mode:
authorYorick Peterse <yorickpeterse@gmail.com>2017-06-29 15:37:37 +0200
committerYorick Peterse <yorickpeterse@gmail.com>2017-06-29 15:37:37 +0200
commitaf1f6844c98bfb4adda1c20dc75b808f031a4256 (patch)
tree7042096cf2b58ed08067f8c24b667226cbf32cf3 /lib/gitlab/database
parent88c60307bd1f215095834f09a1a5cb18701ac8ad (diff)
downloadgitlab-ce-af1f6844c98bfb4adda1c20dc75b808f031a4256.tar.gz
Added code for defining SHA attributes
These attributes are stored in binary in the database, but exposed as strings. This allows one to query/create data using plain SHA1 hashes as Strings, while storing them more efficiently as binary.
Diffstat (limited to 'lib/gitlab/database')
-rw-r--r--lib/gitlab/database/sha_attribute.rb34
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