Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to solve 'Mysql2::Error: This connection is still waiting for a result' error with mysql2 and activerecord

Not duplicate of this question with the same title

I am using activerecord with mysql2 and I am designing to handle 10 queries to the same activerecord model/class at a time. Please note I am using strict activerecord and not using mysql queries directly.

I get the calls in Sinatra and then use activerecord to get the data from the DB.

I don't wan't the calls to be blocking so therefore I used mysql2 and I do NOT want to use em-synchrony.

But now I get the following "Mysql2::Error: This connection is still waiting for a result, try again once you have the result:" on subsequent simultanous calls.

I am not establishing connection with pool=10

my class

  class User < ActiveRecord::Base 

and my code to call user.find(:all, :conditions => ["id=?", userid])

The mysql2 doc says "To use the ActiveRecord driver (with or without rails), all you should need to do is have this gem installed and set the adapter in your database.yml to "mysql2". That was easy right? :)"

And that is exactly what I have done when I moved from mysql to mysql2.

Why am I getting this error.

like image 807
Anand Avatar asked Oct 18 '25 07:10

Anand


1 Answers

Here is a fully working example:

require 'rubygems'
gem 'activerecord', '~> 3.1.0'
gem 'sinatra',      '~> 1.3.1'
gem 'mysql2',       '~> 0.3.11'

require 'active_record'
require 'sinatra/base'
require 'mysql2'

# thin use the eventmachine thread pool
# you should have at least one connection per thread
# or you can expect errors
EM::threadpool_size = 10

# connect to the database
ActiveRecord::Base.establish_connection(
    :adapter => "mysql2",
    :database => "test",
    :username => "root",
    :encoding => 'utf8',
    # number of connections openened to the database
    :pool => 10
  )

class App < Sinatra::Base  
  get '/db' do
    ActiveRecord::Base.connection.execute("SELECT SLEEP(1)")
  end
end

run App

to run it save the file as "config.ru" and run it with thin in threaded mode:

thin start -e production --threaded

You can use ab to check that everything is working, I used a tool called siege:

siege -c 10 -r 1 http://localhost:3000/db
like image 139
Schmurfy Avatar answered Oct 20 '25 12:10

Schmurfy