add initial EM Deferrable API

This commit is contained in:
Brian Lopez 2010-04-14 12:55:27 -07:00
parent 7d6bbbcdd2
commit 288ed22806
3 changed files with 80 additions and 0 deletions

21
examples/eventmachine.rb Normal file
View File

@ -0,0 +1,21 @@
# encoding: utf-8
$LOAD_PATH.unshift 'lib'
require 'rubygems'
require 'eventmachine'
require 'mysql2/em'
EM.run do
client1 = Mysql2::EM::Client.new
defer1 = client1.query "SELECT sleep(3) as first_query"
defer1.callback do |result|
puts "Result: #{result.to_a.inspect}"
end
client2 = Mysql2::EM::Client.new
defer2 = client2.query "SELECT sleep(1) second_query"
defer2.callback do |result|
puts "Result: #{result.to_a.inspect}"
end
end

33
lib/mysql2/em.rb Normal file
View File

@ -0,0 +1,33 @@
# encoding: utf-8
require 'eventmachine' unless defined? EventMachine
require 'mysql2' unless defined? Mysql2
module Mysql2
module EM
class Client < ::Mysql2::Client
module Watcher
def initialize(client, deferable)
@client = client
@deferable = deferable
end
def notify_readable
begin
@deferable.succeed(@client.async_result)
rescue Exception => e
@deferable.fail(e)
end
detach
end
end
def query(sql, opts={})
super(sql, opts.merge(:async => true))
deferable = ::EM::DefaultDeferrable.new
::EM.watch(self.socket, Watcher, self, deferable).notify_readable = true
deferable
end
end
end
end

26
spec/em/em_spec.rb Normal file
View File

@ -0,0 +1,26 @@
# encoding: UTF-8
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')
require 'mysql2/em'
describe Mysql2::EM::Client do
it "should support async queries" do
results = []
EM.run do
client1 = Mysql2::EM::Client.new
defer1 = client1.query "SELECT sleep(0.05) as first_query"
defer1.callback do |result|
results << result.first
EM.stop_event_loop
end
client2 = Mysql2::EM::Client.new
defer2 = client2.query "SELECT sleep(0.025) second_query"
defer2.callback do |result|
results << result.first
end
end
results[0].keys.should include("second_query")
results[1].keys.should include("first_query")
end
end