sha_attribute.rb 995 字节
Newer Older
1 2
# frozen_string_literal: true

3 4
module Gitlab
  module Database
5 6 7
    # PostgreSQL defines its own class with slightly different
    # behaviour from the default Binary type.
    BINARY_TYPE = ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea
8 9 10 11 12 13 14 15 16

    # 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

17
      # Casts binary data to a SHA1 in hexadecimal.
J
Jasper Maes 已提交
18 19
      def deserialize(value)
        value = super(value)
N
Nick Thomas 已提交
20
        value ? value.unpack1(PACK_FORMAT) : nil
21 22 23
      end

      # Casts a SHA1 in hexadecimal to the proper binary format.
24
      def serialize(value)
25 26
        arg = value ? [value].pack(PACK_FORMAT) : nil

J
Jasper Maes 已提交
27
        super(arg)
28 29 30 31
      end
    end
  end
end