How to call MySQL stored procedure from Rails?

Simple stored procedure in MySQL:

CREATE PROCEDURE `proc01`()
BEGIN
 SELECT * FROM users;
END

Launches the Rails console:

$ script/console
Loading development environment (Rails 2.3.5)
>> User.connection.execute("CALL proc01")
=> #<Mysql::Result:0x10343efa0>

Looks nice. BUT, calling the same stored procedure through an existing connection will result in an error. Commands are not synchronized :

>> User.connection.execute("CALL proc01")
ActiveRecord::StatementInvalid: Mysql::Error: Commands out of sync; you can't run this command now: CALL proc01
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract_adapter.rb:219:in `log'
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/mysql_adapter.rb:323:in `execute'
    from (irb):2

The error can be cleared using "reboot!". commands in the console:

>> reload!
Reloading...
=> true
>> User.connection.execute("CALL proc01")
=> #<Mysql::Result:0x1033f14d0>
>> 

How can I call a MySQL stored procedure from Rails?

+5
source share
1 answer

EDIT:

-

Use ActiveRecord::Base.connections.exec_query()is as much as I can say better than MUCH , because it returns an array of hashes, as you would expect, but ActiveRecord::Base.connections.executenot.

-

, , .

, , ohho, , 404'd, .

, :

result = ActiveRecord::Base.connection.execute("call example_proc()") ActiveRecord::Base.clear_active_connections!

, , , , , .

http://apidock.com/rails/v3.2.13/ActiveRecord/Base/clear_active_connections%21/class

- EDIT:

, ActiveRecord leente post

" !

, , . .: ConnectionPool"

connection = ActiveRecord::Base.connection   #WRONG

threads = (1..100).map do
 Thread.new do
begin
  10.times do
    connection.execute("SELECT SLEEP(1)")  # WRONG
    ActiveRecord::Base.connection.execute("SELECT SLEEP(1)")  # CORRECT
  end
  puts "success"
rescue => e
  puts e.message
   end
  end
end

threads.each(&:join) 
+4

All Articles