Class: NeverBlock::DB::PooledDBConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/never_block/db/pooled_db_connection.rb

Overview

a proxy for pooled fibered connections

Instance Method Summary collapse

Constructor Details

#initialize(size = 4, &block) ⇒ PooledDBConnection

Requires a block with connection parameters and a pool size (defaults to 4)



7
8
9
10
11
# File 'lib/never_block/db/pooled_db_connection.rb', line 7

def initialize(size=4, &block)
  @pool = NB::Pool::FiberedConnectionPool.new(:size=>size, :eager=>true) do
    yield
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Pass unknown methods to the connection



57
58
59
60
61
# File 'lib/never_block/db/pooled_db_connection.rb', line 57

def method_missing(method, *args)
  @pool.hold do |conn|
    conn.send(method, *args)
  end        
end

Instance Method Details

#begin_db_transactionObject

This method must be called for transactions to work correctly. One cannot just send “begin” as you never know which connection will be available next. This method ensures you get the same connection while in a transaction.



27
28
29
30
31
# File 'lib/never_block/db/pooled_db_connection.rb', line 27

def begin_db_transaction
  @pool.hold(true) do |conn|
    conn.query("begin")
  end
end

#closeObject

close all connections and remove them from the event loop



50
51
52
53
54
# File 'lib/never_block/db/pooled_db_connection.rb', line 50

def close
  @pool.all_connections do |conn|
    conn.close
  end
end

#commit_db_transactionObject

see =begin_db_transaction



42
43
44
45
46
47
# File 'lib/never_block/db/pooled_db_connection.rb', line 42

def commit_db_transaction
  @pool.hold do |conn|
    conn.query("commit")
    @pool.release(Fiber.current,conn)
  end
end

#query(query) ⇒ Object Also known as: exec

A proxy for the connection’s query method quries the pool to get a connection first



15
16
17
18
19
# File 'lib/never_block/db/pooled_db_connection.rb', line 15

def query(query)
  @pool.hold do |conn|
    conn.query(query)
  end
end

#respond_to?(method) ⇒ Boolean

Pass method queries to the connection

Returns:

  • (Boolean)


64
65
66
67
68
# File 'lib/never_block/db/pooled_db_connection.rb', line 64

def respond_to?(method)
  @pool.hold do |conn|
    conn.respond_to?(method)
  end        
end

#rollback_db_transactionObject

see =begin_db_transaction



34
35
36
37
38
39
# File 'lib/never_block/db/pooled_db_connection.rb', line 34

def rollback_db_transaction
  @pool.hold do |conn|
    conn.query("rollback")
    @pool.release(Fiber.current,conn)
  end
end