BigW Consortium Gitlab

database.rb 1.82 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 42 43 44
    def self.serialized_transaction
      opts = {}
      opts[:isolation] = :serializable unless Rails.env.test? && connection.transaction_open?

      connection.transaction(opts) { yield }
    end

45 46 47 48
    def self.random
      Gitlab::Database.postgresql? ? "RANDOM()" : "RAND()"
    end

49
    def true_value
50
      if Gitlab::Database.postgresql?
51 52 53 54 55 56 57
        "'t'"
      else
        1
      end
    end

    def false_value
58
      if Gitlab::Database.postgresql?
59 60 61 62 63
        "'f'"
      else
        0
      end
    end
64 65 66 67 68

    def self.connection
      ActiveRecord::Base.connection
    end

69 70
    private_class_method :connection

71 72 73 74 75 76 77 78 79
    def self.database_version
      row = connection.execute("SELECT VERSION()").first

      if postgresql?
        row['version']
      else
        row.first
      end
    end
80 81

    private_class_method :database_version
82 83
  end
end