Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
AbstractAdapter
  • Object
show all
Defined in:
lib/active_record_postgresql_retry.rb

Constant Summary collapse

PG_SLEEP_RETRY =
ENV['PG_SLEEP_RETRY'].to_f || 0.33
PG_QUERY_RETRY =
ENV['PG_QUERY_RETRY'].to_i || 0
PG_RECONNECT_RETRY =
ENV['PG_RECONNECT_RETRY'].to_i || 0
PG_CONNECT_RETRY =
ENV['PG_CONNECT_RETRY'].to_i || 0

Instance Method Summary collapse

Instance Method Details

#connectObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/active_record_postgresql_retry.rb', line 57

def connect

  begin
    result = old_connect
    @retry = nil
    result
  rescue PG::Error => ex
    @retry ||= 1
    $log.warn "PostgreSQL connect not possible, retry ##{@retry}: #{ex}"
    sleep PG_SLEEP_RETRY
    @retry += 1
    raise if @retry > PG_CONNECT_RETRY
  end

  if @retry.nil?
    result
  else
    connect
  end

end

#execute(sql, name = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/active_record_postgresql_retry.rb', line 15

def execute(sql, name=nil)
  begin
    result = old_execute(sql, name)
    @retry = nil
    result
  rescue PG::ConnectionBad, PG::UnableToSend => ex
    @retry ||= 1
    $log.warn "PostgreSQL statement invalid, retrying #{sql}: #{ex}"
    sleep PG_SLEEP_RETRY
    @retry += 1
    raise if @retry > PG_QUERY_RETRY
  end

  if @retry.nil?
    result
  else
    execute(sql, name)
  end

end

#old_connectObject



8
# File 'lib/active_record_postgresql_retry.rb', line 8

alias_method :old_connect, :connect

#old_executeObject



6
# File 'lib/active_record_postgresql_retry.rb', line 6

alias_method :old_execute, :execute

#old_reconnect!Object



7
# File 'lib/active_record_postgresql_retry.rb', line 7

alias_method :old_reconnect!, :reconnect!

#reconnect!Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_record_postgresql_retry.rb', line 36

def reconnect!
  begin
    result = old_reconnect!
    @retry = nil
    result
  rescue PG::Error => ex
    @retry ||= 1
    $log.warn "PostgreSQL reconnect not possible, retry ##{@retry}: #{ex}"
    sleep PG_SLEEP_RETRY
    @retry += 1
    raise if @retry > PG_RECONNECT_RETRY
  end

  if @retry.nil?
    result
  else
    reconnect!
  end

end