Class: DB::Client

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

Overview

Binds a connection pool to the specified adapter.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter, **options) ⇒ Client

Initialize the client and internal connection pool using the specified adapter.



17
18
19
20
21
# File 'lib/db/client.rb', line 17

def initialize(adapter, **options)
	@adapter = adapter
	
	@pool = connect(**options)
end

Instance Attribute Details

#adapterObject

The adapter used for making connections.



25
26
27
# File 'lib/db/client.rb', line 25

def adapter
  @adapter
end

Instance Method Details

#closeObject

Close all open connections in the connection pool.



28
29
30
# File 'lib/db/client.rb', line 28

def close
	@pool.close
end

#context(**options) ⇒ Object

Acquire a generic context which will acquire a connection on demand.



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/db/client.rb', line 33

def context(**options)
	context = Context::Transient.new(@pool, **options)
	
	return context unless block_given?
	
	begin
		yield context
	ensure
		context.close
	end
end

#session(**options) ⇒ Object

Acquires a connection and sends the specified statement if given.



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/db/client.rb', line 50

def session(**options)
	session = Context::Session.new(@pool, **options)
	
	return session unless block_given?
	
	begin
		yield session
	ensure
		session.close
	end
end

#transaction(**options) ⇒ Object

Acquires a connection and starts a transaction.



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/db/client.rb', line 67

def transaction(**options)
	transaction = Context::Transaction.new(@pool, **options)
	
	transaction.call("BEGIN")
	
	return transaction unless block_given?
	
	begin
		yield transaction
		
	rescue
		transaction.abort
		raise
	ensure
		transaction.commit?
	end
end