Skip to content

Commit

Permalink
Merge pull request #10 from nvreynolds/retry-db-connection-logic
Browse files Browse the repository at this point in the history
retry db connection logic
  • Loading branch information
nvreynolds authored Apr 24, 2019
2 parents 6c130f0 + 28e9125 commit f1d1fd6
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 11 deletions.
4 changes: 2 additions & 2 deletions factory_bro.gemspec
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Gem::Specification.new do |s|
s.name = 'factory_bro'
s.licenses = ['MIT']
s.version = '0.0.8'
s.date = '2019-03-13'
s.version = '0.0.9'
s.date = '2019-04-24'
s.summary = "Factory Bro"
s.description = "PSQL Parser and Data Generation similar to factory_girl"
s.authors = ["Nate Reynolds"]
Expand Down
50 changes: 41 additions & 9 deletions lib/factory_bro.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,36 @@ def self.connect(name, db)
$conns = {}
else
$conns.each do |key, conn|
if conn.finished?
if conn&.finished?
$conns[key] = ''
end
end
end
unless $dbs
$dbs = {}
end
$dbs[name] = db
if db.include? 'postgres://'
dbData = parse_url(db)
$conns[name] = PG.connect( user: dbData[:user],
password: dbData[:pw],
host: dbData[:host],
port: dbData[:port],
dbname: dbData[:dbname]
)
$conns[name] = safe_connect(name) do
PG.connect(
user: dbData[:user],
password: dbData[:pw],
host: dbData[:host],
port: dbData[:port],
dbname: dbData[:dbname]
)
end
else
# take arguments of user and pw
$conns[name] = PG.connect( dbname: db)
$conns[name] = safe_connect { PG.connect(dbname: db) }
end
end

def self.close(name)
$conns[name].finish
$conns[name] = ''
$dbs[name] = ''
end

def self.close_all
Expand All @@ -39,10 +47,12 @@ def self.close_all
end
end
$conns = nil
$dbs = nil
end

def self.exec(name, statement)
run = $conns[name].exec(statement)
run = safe_connect(name) { $conns[name].exec(statement) }
$try = 0
run.values
end

Expand Down Expand Up @@ -154,4 +164,26 @@ def self.generate_helper(data)
end
{ columns: columns, values: values}
end

def self.safe_connect(name)
$try ||= 0
max_tries = 4
wait = 10
success = false
result = nil
until success
begin
result = yield
success = true
result
rescue PG::UnableToSend, PG::ConnectionBad => error
$try += 1
raise error if $try > max_tries
puts "FactoryBro error: Failed to connect to #{name}, try ##{$try} to reconnect in #{wait}s"
sleep wait
connect(name, $dbs[name])
end
end
result
end
end

0 comments on commit f1d1fd6

Please sign in to comment.