debian-mirror-gitlab/lib/gitlab/database/sha_attribute.rb

37 lines
1.1 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2017-09-10 17:25:29 +05:30
module Gitlab
module Database
2018-05-09 12:01:36 +05:30
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
2019-02-15 15:39:39 +05:30
ActiveModel::Type::Binary
2018-05-09 12:01:36 +05:30
end
2017-09-10 17:25:29 +05:30
# 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
2018-05-09 12:01:36 +05:30
# Casts binary data to a SHA1 in hexadecimal.
2019-02-15 15:39:39 +05:30
def deserialize(value)
value = super(value)
2019-05-18 00:54:41 +05:30
value ? value.unpack1(PACK_FORMAT) : nil
2017-09-10 17:25:29 +05:30
end
# Casts a SHA1 in hexadecimal to the proper binary format.
2018-05-09 12:01:36 +05:30
def serialize(value)
2017-09-10 17:25:29 +05:30
arg = value ? [value].pack(PACK_FORMAT) : nil
2019-02-15 15:39:39 +05:30
super(arg)
2017-09-10 17:25:29 +05:30
end
end
end
end