debian-mirror-gitlab/app/models/application_record.rb

86 lines
1.7 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
2019-03-02 22:35:43 +05:30
2019-07-31 22:56:46 +05:30
alias_method :reset, :reload
2020-06-23 00:09:42 +05:30
def self.without_order
reorder(nil)
end
2019-03-02 22:35:43 +05:30
def self.id_in(ids)
where(id: ids)
end
2020-11-24 15:15:51 +05:30
def self.primary_key_in(values)
where(primary_key => values)
end
2020-07-28 23:09:34 +05:30
def self.iid_in(iids)
where(iid: iids)
end
2019-07-07 11:18:12 +05:30
def self.id_not_in(ids)
where.not(id: ids)
end
def self.pluck_primary_key
where(nil).pluck(self.primary_key)
end
2019-05-03 19:53:19 +05:30
def self.safe_ensure_unique(retries: 0)
transaction(requires_new: true) do
yield
end
rescue ActiveRecord::RecordNotUnique
if retries > 0
retries -= 1
retry
end
false
end
2020-07-28 23:09:34 +05:30
def self.at_most(count)
limit(count)
end
2020-10-24 23:57:45 +05:30
def self.safe_find_or_create_by!(*args, &block)
safe_find_or_create_by(*args, &block).tap do |record|
2021-01-29 00:20:46 +05:30
raise ActiveRecord::RecordNotFound unless record.present?
2019-03-02 22:35:43 +05:30
record.validate! unless record.persisted?
end
end
2021-01-03 14:25:43 +05:30
# Start a new transaction with a shorter-than-usual statement timeout. This is
# currently one third of the default 15-second timeout
def self.with_fast_statement_timeout
transaction(requires_new: true) do
connection.exec_query("SET LOCAL statement_timeout = 5000")
yield
end
end
2020-10-24 23:57:45 +05:30
def self.safe_find_or_create_by(*args, &block)
2019-05-03 19:53:19 +05:30
safe_ensure_unique(retries: 1) do
2020-10-24 23:57:45 +05:30
find_or_create_by(*args, &block)
2019-03-02 22:35:43 +05:30
end
end
2019-09-04 21:01:54 +05:30
def self.underscore
Gitlab::SafeRequestStore.fetch("model:#{self}:underscore") { self.to_s.underscore }
end
2021-01-03 14:25:43 +05:30
def self.where_exists(query)
where('EXISTS (?)', query.select(1))
end
2021-03-08 18:12:59 +05:30
def self.declarative_enum(enum_mod)
values = enum_mod.definition.transform_values { |v| v[:value] }
enum(enum_mod.key => values)
end
2019-02-15 15:39:39 +05:30
end