Browse Source

[ruby/sinatra] Return db connections to the pool. (#8443)

* [ruby/sinatra] Fix update

Make sure randomnumber is actually a different value.

* [ruby/sinatra] Return db connections to the pool.

This resolves the following errors for Fortunes:

      ActiveRecord::ConnectionTimeoutError - could not obtain a connection
      from the pool within 10.000 seconds (waited 10.010 seconds); all pooled
      connections were in use:

This is also what is used by Sinatra-ActiveRecord:

https://github.com/sinatra-activerecord/sinatra-activerecord/commit/85e35341175e0b47e49b3d71ec3bf4fc5e61009d#diff-a8d61b0c6c1526535937f4851a83d8b0R33

This also requires running ActiveRecord < 5.1 and updates the `pg` gem.
Petrik de Heus 1 year ago
parent
commit
5f12397bda
2 changed files with 9 additions and 3 deletions
  1. 2 2
      frameworks/Ruby/sinatra/Gemfile
  2. 7 1
      frameworks/Ruby/sinatra/hello_world.rb

+ 2 - 2
frameworks/Ruby/sinatra/Gemfile

@@ -1,6 +1,6 @@
 source 'https://rubygems.org'
 
-gem 'activerecord', '~> 5.0', :require=>'active_record'
+gem 'activerecord', '~> 5.0.0', :require=>'active_record'
 gem 'activerecord-jdbc-adapter', '>= 5.0.pre1', '< 6.0', :platforms=>:jruby
 gem 'json', '~> 2.0'
 gem 'passenger', '~> 5.1', :platforms=>[:ruby, :mswin], :require=>false
@@ -16,5 +16,5 @@ end
 
 group :postgresql do
   gem 'jdbc-postgres', '~> 9.4', :platforms=>:jruby, :require=>'jdbc/postgres'
-  gem 'pg', '~> 0.19', :platforms=>[:ruby, :mswin]
+  gem 'pg', '1.2.3', :platforms=>[:ruby, :mswin]
 end

+ 7 - 1
frameworks/Ruby/sinatra/hello_world.rb

@@ -41,6 +41,10 @@ class HelloWorld < Sinatra::Base
     response['Server'] = SERVER_STRING
   end if SERVER_STRING
 
+  after do
+    ActiveRecord::Base.clear_active_connections!
+  end
+
   # Test type 1: JSON serialization
   get '/json' do
      json :message=>'Hello, World!'
@@ -88,7 +92,9 @@ class HelloWorld < Sinatra::Base
       ActiveRecord::Base.connection_pool.with_connection do
         Array.new(bounded_queries) do
           world = World.find(rand1)
-          world.update(:randomnumber=>rand1)
+          new_value = rand1
+          new_value = rand1 while new_value == world.randomnumber
+          world.update(randomnumber: new_value)
           world
         end
       end