v / vlib / db / mysql / pool.v
38 lines · 33 sloc · 971 bytes · 7039081d66b63e5c914b640d93e620889a18a693
Raw
1module mysql
2
3pub struct ConnectionPool {
4mut:
5 connections chan DB
6 config Config
7}
8
9// new_connection_pool creates a new connection pool with the given size and configuration.
10pub 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
23pub 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.
28pub fn (mut pool ConnectionPool) release(conn DB) {
29 pool.connections <- conn
30}
31
32// close closes all connections in the pool.
33pub fn (mut pool ConnectionPool) close() {
34 for _ in 0 .. pool.connections.len {
35 mut conn := <-pool.connections or { break }
36 conn.close() or { break }
37 }
38}
39