2023-07-12 15:06:00 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DatabaseHelper
|
2023-09-22 14:01:59 +00:00
|
|
|
def replica_enabled?
|
|
|
|
ENV['REPLICA_DB_NAME'] || ENV.fetch('REPLICA_DATABASE_URL', nil)
|
|
|
|
end
|
|
|
|
module_function :replica_enabled?
|
|
|
|
|
2023-07-12 15:06:00 +00:00
|
|
|
def with_read_replica(&block)
|
2023-09-22 14:01:59 +00:00
|
|
|
if replica_enabled?
|
|
|
|
ApplicationRecord.connected_to(role: :reading, prevent_writes: true, &block)
|
|
|
|
else
|
|
|
|
yield
|
|
|
|
end
|
2023-07-12 15:06:00 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def with_primary(&block)
|
2023-09-22 14:01:59 +00:00
|
|
|
if replica_enabled?
|
|
|
|
ApplicationRecord.connected_to(role: :writing, &block)
|
|
|
|
else
|
|
|
|
yield
|
|
|
|
end
|
2023-07-12 15:06:00 +00:00
|
|
|
end
|
|
|
|
end
|