2018-11-05 23:45:35 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-06-29 09:37:37 -04:00
|
|
|
module Gitlab
|
|
|
|
module Database
|
2019-07-24 09:59:55 -04:00
|
|
|
# PostgreSQL defines its own class with slightly different
|
|
|
|
# behaviour from the default Binary type.
|
|
|
|
BINARY_TYPE = ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea
|
2017-06-29 09:37:37 -04:00
|
|
|
|
|
|
|
# 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
|
2019-08-31 15:25:25 -04:00
|
|
|
PACK_FORMAT = 'H*'
|
2017-06-29 09:37:37 -04:00
|
|
|
|
2018-04-06 06:57:19 -04:00
|
|
|
# Casts binary data to a SHA1 in hexadecimal.
|
2018-12-15 04:06:56 -05:00
|
|
|
def deserialize(value)
|
|
|
|
value = super(value)
|
2019-03-13 09:42:43 -04:00
|
|
|
value ? value.unpack1(PACK_FORMAT) : nil
|
2017-06-29 09:37:37 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# Casts a SHA1 in hexadecimal to the proper binary format.
|
2018-04-06 06:57:19 -04:00
|
|
|
def serialize(value)
|
2017-06-29 09:37:37 -04:00
|
|
|
arg = value ? [value].pack(PACK_FORMAT) : nil
|
|
|
|
|
2020-01-29 10:08:59 -05:00
|
|
|
BINARY_TYPE.new.serialize(arg)
|
|
|
|
end
|
|
|
|
|
|
|
|
# Casts a SHA1 in hexadecimal to the proper binary format.
|
|
|
|
def self.serialize(value)
|
|
|
|
arg = value ? [value].pack(PACK_FORMAT) : nil
|
|
|
|
|
|
|
|
BINARY_TYPE.new.serialize(arg)
|
2017-06-29 09:37:37 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|