Class: NeverBlock::DB::PooledFiberedPostgresConnection

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

Overview

A pooled postgres connection class. This class represents a proxy interface to a connection pool of fibered postgresql connections.

Instance Method Summary collapse

Constructor Details

#initialize(conn_params, size = 4) ⇒ PooledFiberedPostgresConnection

Requires a hash or an array with connection parameters and a pool size (defaults to 4)



11
12
13
14
15
16
17
18
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 11

def initialize(conn_params, size=4)
  @pool = NB::Pool::FiberedConnectionPool.new(:size=>size, :eager=>true) do
    conn = NB::DB::FPGconn.new(*conn_params) if conn_params.is_a? Array
    conn = NB::DB::FPGconn.new(conn_params) if conn_params.is_a? Hash          
   conn.register_with_event_loop(:em)
    conn          
  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



55
56
57
58
59
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 55

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.



32
33
34
35
36
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 32

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

#commit_db_transactionObject

see =begin_db_transaction



47
48
49
50
51
52
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 47

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

#exec(query) ⇒ Object

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



22
23
24
25
26
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 22

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

#respond_to?(method) ⇒ Boolean

Pass method queries to the connection

Returns:

  • (Boolean)


62
63
64
65
66
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 62

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

#rollback_db_transactionObject

see =begin_db_transaction



39
40
41
42
43
44
# File 'lib/never_block/db/pooled_fibered_postgres_connection.rb', line 39

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