| 1 | module pg |
| 2 | |
| 3 | pub struct ConnectionPool { |
| 4 | mut: |
| 5 | connections chan DB |
| 6 | config Config |
| 7 | } |
| 8 | |
| 9 | // new_connection_pool creates a new connection pool with the given size and configuration. |
| 10 | pub fn new_connection_pool(config Config, size int) !ConnectionPool { |
| 11 | mut connections := chan DB{cap: size} |
| 12 | for _ in 0 .. size { |
| 13 | conn := connect(config)! |
| 14 | connections <- conn |
| 15 | } |
| 16 | return ConnectionPool{ |
| 17 | connections: connections |
| 18 | config: config |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | // acquire gets a connection from the pool |
| 23 | pub fn (mut pool ConnectionPool) acquire() !DB { |
| 24 | return <-pool.connections or { return error('Failed to acquire a connection from the pool') } |
| 25 | } |
| 26 | |
| 27 | // release returns a connection back to the pool. |
| 28 | pub fn (mut pool ConnectionPool) release(conn DB) { |
| 29 | pool.connections <- conn |
| 30 | } |
| 31 | |
| 32 | // close closes all connections in the pool. |
| 33 | pub fn (mut pool ConnectionPool) close() { |
| 34 | for _ in 0 .. pool.connections.len { |
| 35 | conn := <-pool.connections or { break } |
| 36 | conn.close() or { break } |
| 37 | } |
| 38 | } |
| 39 | |