Simple database connection pooling implementation compatible with Fiber ORM.
Types
DbConnPool = ref object conns: seq[PooledDbConn] cfg: DbConnPoolConfig lastId: int
- Database connection pool Source Edit
DbConnPoolConfig = object connect*: () -> DbConn ## Factory procedure to create a new DBConn poolSize*: int ## The pool capacity. hardCap*: bool ## Is the pool capacity a hard cap? ## ## When `false`, the pool can grow beyond the configured ## capacity, but will release connections down to the its ## capacity (no less than `poolSize`). ## ## When `true` the pool will not create more than its ## configured capacity. It a connection is requested, none ## are free, and the pool is at capacity, this will result ## in an Error being raised. healthCheckQuery*: string ## Should be a simple and fast SQL query that the ## pool can use to test the liveliness of pooled ## connections.
- Source Edit
Procs
proc initDbConnPool(cfg: DbConnPoolConfig): DbConnPool {....raises: [Exception], tags: [RootEffect].}
- Source Edit
proc release(pool: DbConnPool; connId: int): void {. ...raises: [Exception, ValueError], tags: [RootEffect].}
- Release a connection back to the pool. Source Edit
proc take(pool: DbConnPool): tuple[id: int, conn: DbConn] {. ...raises: [Exception, ValueError], tags: [RootEffect, ReadDbEffect, DbEffect].}
-
Request a connection from the pool. Returns a DbConn if the pool has free connections, or if it has the capacity to create a new connection. If the pool is configured with a hard capacity limit and is out of free connections, this will raise an Error.
Connections taken must be returned via release when the caller is finished using them in order for them to be released back to the pool.
Source Edit
Templates
template withConn(pool: DbConnPool; stmt: untyped): untyped
-
Convenience template to provide a connection from the pool for use in a statement block, automatically releasing that connnection when done.
The provided connection is injected as the variable conn in the statement body.
Source Edit