BigW Consortium Gitlab

database.rb 1.62 KB
Newer Older
1 2
module Gitlab
  module Database
3 4 5 6 7
    # The max value of INTEGER type is the same between MySQL and PostgreSQL:
    # https://www.postgresql.org/docs/9.2/static/datatype-numeric.html
    # http://dev.mysql.com/doc/refman/5.7/en/integer-types.html
    MAX_INT_VALUE = 2147483647

8 9 10 11
    def self.adapter_name
      connection.adapter_name
    end

12
    def self.mysql?
13
      adapter_name.casecmp('mysql2').zero?
14 15 16
    end

    def self.postgresql?
17
      adapter_name.casecmp('postgresql').zero?
18 19 20 21
    end

    def self.version
      database_version.match(/\A(?:PostgreSQL |)([^\s]+).*\z/)[1]
22
    end
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37
    def self.nulls_last_order(field, direction = 'ASC')
      order = "#{field} #{direction}"

      if Gitlab::Database.postgresql?
        order << ' NULLS LAST'
      else
        # `field IS NULL` will be `0` for non-NULL columns and `1` for NULL
        # columns. In the (default) ascending order, `0` comes first.
        order.prepend("#{field} IS NULL, ") if direction == 'ASC'
      end

      order
    end

38 39 40 41
    def self.random
      Gitlab::Database.postgresql? ? "RANDOM()" : "RAND()"
    end

42
    def true_value
43
      if Gitlab::Database.postgresql?
44 45 46 47 48 49 50
        "'t'"
      else
        1
      end
    end

    def false_value
51
      if Gitlab::Database.postgresql?
52 53 54 55 56
        "'f'"
      else
        0
      end
    end
57 58 59 60 61

    def self.connection
      ActiveRecord::Base.connection
    end

62 63
    private_class_method :connection

64 65 66 67 68 69 70 71 72
    def self.database_version
      row = connection.execute("SELECT VERSION()").first

      if postgresql?
        row['version']
      else
        row.first
      end
    end
73 74

    private_class_method :database_version
75 76
  end
end