From 288ed22806a93636c0469d50460e634424218459 Mon Sep 17 00:00:00 2001 From: Brian Lopez Date: Wed, 14 Apr 2010 12:55:27 -0700 Subject: [PATCH] add initial EM Deferrable API --- examples/eventmachine.rb | 21 +++++++++++++++++++++ lib/mysql2/em.rb | 33 +++++++++++++++++++++++++++++++++ spec/em/em_spec.rb | 26 ++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 examples/eventmachine.rb create mode 100644 lib/mysql2/em.rb create mode 100644 spec/em/em_spec.rb diff --git a/examples/eventmachine.rb b/examples/eventmachine.rb new file mode 100644 index 0000000..a92ca4c --- /dev/null +++ b/examples/eventmachine.rb @@ -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 \ No newline at end of file diff --git a/lib/mysql2/em.rb b/lib/mysql2/em.rb new file mode 100644 index 0000000..6d95549 --- /dev/null +++ b/lib/mysql2/em.rb @@ -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 \ No newline at end of file diff --git a/spec/em/em_spec.rb b/spec/em/em_spec.rb new file mode 100644 index 0000000..d20f27f --- /dev/null +++ b/spec/em/em_spec.rb @@ -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 \ No newline at end of file