在我们的Ruby代码中,有三行(目前用于调试目的)看起来像这样:
puts "Established connection to: " \
"#{ActiveRecord::Base.establish_connection(database_config).spec.config}"
puts "Connection is connected to: " \
"#{ActiveRecord::Base.connection.instance_eval{@config.inspect}}
ActiveRecord::Base.connection.execute("SELECT 1") # Test connection
当点击此代码时,第一行始终打印
Established connection to: {:username=>"name", :host=>"localhost", :password=>"pass",
:adapter=>"mysql", :database=>"database1"}
通知我们已成功建立连接。通常,第二行和第三行按预期执行,一切都顺利进行。然后第二行产生相同的结果:
Connection is connected to: {:username=>"name", :host=>"localhost", :password=>"pass",
:adapter=>"mysql", :database=>"database1"}
但是,出于某种原因,每隔一段时间(例如,在执行几百个测试用例期间两次),第二行产生:
Connection is connected to: {:username=>"name", :host=>"localhost", :password=>"pass",
:adapter=>"mysql", :database=>"database2"}
(注意不同的数据库),第三行失败
Mysql::Error: query: not connected: SELECT 1
$APP_ROOT/vendor/bundle/ruby/1.8/gems/activerecord-3.0.4/lib/active_record/connection_adapters/abstract_adapter.rb:207:in `log': Mysql::Error: query: not connected: SELECT 1 (ActiveRecord::StatementInvalid)
from $APP_ROOT/vendor/bundle/ruby/1.8/gems/activerecord-3.0.4/lib/active_record/connection_adapters/mysql_adapter.rb:289:in `execute'
from $APP_ROOT/somewhere_in_our_code.rb:84:in `establish_database_connection' (which is the third line quoted above)
(我认为你可以忽略那里的“StatementInvalid”:这是一个有效的MySQL查询,在这条消息中使用StatementInvalid似乎是ActiveRecord代码中的一个小错误)
因此,出于某种原因,在建立连接和获取绑定到线程的连接之间,ActiveRecord会感到困惑。有谁知道为什么会发生这种情况?
CentOS Linux,Ruby 1.8.7(企业版2011.03),Rails 3.0.4,MySQL 2.8.1。
您可以在网上找到的此错误的几乎所有情况都涉及降级Windows系统上的mysql DLL,这在此处不适用。