lib/distribute_reads.rb in distribute_reads-0.2.1 vs lib/distribute_reads.rb in distribute_reads-0.2.2
- old
+ new
@@ -27,16 +27,17 @@
def self.lag(connection: nil)
raise DistributeReads::Error, "Don't use outside distribute_reads" unless Thread.current[:distribute_reads]
connection ||= ActiveRecord::Base.connection
- if %w(PostgreSQL PostGIS).include?(connection.adapter_name)
- replica_pool = connection.instance_variable_get(:@slave_pool)
- if replica_pool && replica_pool.connections.size > 1
- warn "[distribute_reads] Multiple replicas available, lag only reported for one"
- end
+ replica_pool = connection.instance_variable_get(:@slave_pool)
+ if replica_pool && replica_pool.connections.size > 1
+ warn "[distribute_reads] Multiple replicas available, lag only reported for one"
+ end
+
+ if %w(PostgreSQL PostGIS).include?(connection.adapter_name)
# cache the version number
@server_version_num ||= {}
cache_key = connection.pool.object_id
@server_version_num[cache_key] ||= connection.execute("SHOW server_version_num").first["server_version_num"].to_i
@@ -51,9 +52,19 @@
"SELECT CASE
WHEN NOT pg_is_in_recovery() OR #{lag_condition} THEN 0
ELSE EXTRACT (EPOCH FROM NOW() - pg_last_xact_replay_timestamp())
END AS lag".squish
).first["lag"].to_f
+ elsif %w(MySQL Mysql2 Mysql2Spatial Mysql2Rgeo).include?(connection.adapter_name)
+ replica_value = Thread.current[:distribute_reads][:replica]
+ begin
+ # makara doesn't send SHOW queries to replica, so we must force it
+ Thread.current[:distribute_reads][:replica] = true
+ status = connection.exec_query("SHOW SLAVE STATUS").to_hash.first
+ status ? status["Seconds_Behind_Master"].to_f : 0.0
+ ensure
+ Thread.current[:distribute_reads][:replica] = replica_value
+ end
else
raise DistributeReads::Error, "Option not supported with this adapter"
end
end