Permalink
Browse files

async activerecord wrapper (via em-synchrony)

  • Loading branch information...
1 parent bde923d commit 17739531796e025959b5b7e0c42c35a13440382f @igrigorik committed Apr 13, 2010
@@ -0,0 +1,54 @@
+gem 'activerecord', '>= 2.3.4'
+
+require 'activerecord'
+require 'active_record/connection_adapters/mysql_adapter'
+require 'em-synchrony'
+
+module ActiveRecord
+ module ConnectionAdapters
+
+ class EmMysqlAdapter < MysqlAdapter
+
+ def initialize(connection, logger, host_parameters, connection_parameters, config)
+ @hostname = host_parameters[0]
+ @port = host_parameters[1]
+ @connect_parameters, @config = connection_parameters, config
+ super(connection, logger, nil, config)
+ end
+
+ def connect
+ @connection = EventMachine::Synchrony::ConnectionPool.new(size: @config[:fiber_pool]) do
+ EventMachine::MySQL.new({
+ :host => @hostname,
+ :port => @port,
+ :database => @config[:database],
+ :password => @config[:password],
+ :socket => @config[:socket]
+ })
+ end
+
+ configure_connection
+ @connection
+ end
+
+ end
+ end
+
+ class Base
+ def self.em_mysqlplus_connection(config) # :nodoc:
+ config = config.symbolize_keys
+ host = config[:host]
+ port = config[:port]
+ username = config[:username].to_s if config[:username]
+ password = config[:password].to_s if config[:password]
+
+ if config.has_key?(:database)
+ database = config[:database]
+ else
+ raise ArgumentError, "No database specified. Missing argument: database."
+ end
+
+ ConnectionAdapters::EmMysqlAdapter.new(nil, logger, [host, port], [database, username, password], config)
+ end
+ end
+end
@@ -0,0 +1,3 @@
+$:.unshift(File.dirname(__FILE__) + '/../lib')
+
+require 'active_record/connection_adapters/em_mysqlplus_adapter'
@@ -0,0 +1,33 @@
+require 'helper'
+require 'logger'
+require 'yaml'
+require 'erb'
+
+require 'lib/em-activerecord'
+
+RAILS_ENV='test'
+
+ActiveRecord::Base.configurations = YAML::load(ERB.new(File.read(File.join(File.dirname(__FILE__), 'database.yml'))).result)
+ActiveRecord::Base.default_timezone = :utc
+ActiveRecord::Base.logger = Logger.new(STDOUT)
+ActiveRecord::Base.logger.level = Logger::INFO
+ActiveRecord::Base.pluralize_table_names = false
+ActiveRecord::Base.time_zone_aware_attributes = true
+Time.zone = 'UTC'
+
+class Widget < ActiveRecord::Base; end
+
+
+describe "ActiveRecord Driver for EM-MySQLPlus" do
+ it "should establish AR connection" do
+ EventMachine.run {
+ Fiber.new {
+ ActiveRecord::Base.establish_connection
+ result = ActiveRecord::Base.connection.query('select sleep(1)')
+ p result
+
+ EventMachine.stop
+ }.resume
+ }
+ end
+end
View
@@ -0,0 +1,5 @@
+test:
+ adapter: em_mysqlplus
+ database: widgets
+ pool: 1
+ fiber_pool: 1

0 comments on commit 1773953

Please sign in to comment.