Class: Pgtk::Pool
- Inherits:
-
Object
- Object
- Pgtk::Pool
- Defined in:
- lib/pgtk/pool.rb
Overview
Pool.
- Author
-
Yegor Bugayenko ([email protected])
- Copyright
-
Copyright © 2019 Yegor Bugayenko
- License
-
MIT
Instance Method Summary collapse
-
#connect ⇒ Object
Get a connection from the pool and let us work with it.
-
#exec(query, args = [], result = 0) ⇒ Object
Make a query and return the result as an array of hashes.
-
#initialize(host: 'localhost', port:, dbname:, user:, password:) ⇒ Pool
constructor
Constructor.
-
#start(max = 1) ⇒ Object
Start it with a fixed number of connections.
Constructor Details
#initialize(host: 'localhost', port:, dbname:, user:, password:) ⇒ Pool
Constructor.
32 33 34 35 36 37 38 39 40 |
# File 'lib/pgtk/pool.rb', line 32 def initialize(host: 'localhost', port:, dbname:, user:, password:) @host = host @port = port @port = port @dbname = dbname @user = user @password = password @pool = Queue.new end |
Instance Method Details
#connect ⇒ Object
Get a connection from the pool and let us work with it. The block has to be provided, for example:
pgsql.connect do |c|
c.transaction do |conn|
conn.exec_params('DELETE FROM user WHERE id = $1', [id])
conn.exec_params('INSERT INTO user (name) VALUES ($1)', [name])
end
end
77 78 79 80 81 82 83 84 |
# File 'lib/pgtk/pool.rb', line 77 def connect conn = @pool.pop begin yield conn ensure @pool << conn end end |
#exec(query, args = [], result = 0) ⇒ Object
Make a query and return the result as an array of hashes.
54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/pgtk/pool.rb', line 54 def exec(query, args = [], result = 0) connect do |c| c.exec_params(query, args, result) do |res| if block_given? yield res else rows = [] res.each { |r| rows << r } rows end end end end |
#start(max = 1) ⇒ Object
Start it with a fixed number of connections.
43 44 45 46 47 48 49 50 51 |
# File 'lib/pgtk/pool.rb', line 43 def start(max = 1) max.times do @pool << PG.connect( dbname: @dbname, host: @host, port: @port, user: @user, password: @password ) end self end |