summaryrefslogtreecommitdiff
path: root/app/models/site_statistic.rb
blob: 51aa75e0d1f1114ccceeb91c4ce57c098cf10b65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class SiteStatistic < ActiveRecord::Base
  # prevents the creation of multiple rows
  default_value_for :id, 1

  COUNTER_ATTRIBUTES = %w(repositories_count wikis_count).freeze

  # https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
  MYSQL_NO_SUCH_TABLE = 1146

  def self.track(raw_attribute)
    with_statistics_available(raw_attribute) do |attribute|
      SiteStatistic.update_all(["#{attribute} = #{attribute}+1"])
    end
  end

  def self.untrack(raw_attribute)
    with_statistics_available(raw_attribute) do |attribute|
      SiteStatistic.update_all(["#{attribute} = #{attribute}-1 WHERE #{attribute} > 0"])
    end
  end

  def self.with_statistics_available(raw_attribute)
    unless raw_attribute.in?(COUNTER_ATTRIBUTES)
      raise ArgumentError, "Invalid attribute: '#{raw_attribute}' to '#{caller_locations(1, 1)[0].label}' method. " \
                           "Valid attributes are: #{COUNTER_ATTRIBUTES.join(', ')}"
    end

    # we have quite a lot of specs testing migrations, we need this and the rescue to not break them
    SiteStatistic.transaction(requires_new: true) do
      SiteStatistic.first_or_create if Rails.env.test? # make sure SiteStatistic exists during tests
      attribute = self.connection.quote_column_name(raw_attribute)

      yield(attribute)
    end
  rescue ActiveRecord::StatementInvalid => ex
    # we want to ignore this so we don't break the migration specs
    unless ex.original_exception.is_a?(PG::UndefinedTable) ||
        (ex.original_exception.is_a?(Mysql2::Error) && ex.original_exception.error_number == MYSQL_NO_SUCH_TABLE)
      raise ex
    end
  end

  def self.fetch
    SiteStatistic.first_or_create!
  end
end