glimr/db/pool
Connection Pooling
Provides connection pooling for both PostgreSQL and SQLite. PostgreSQL uses pog’s built-in pooling. SQLite uses a simple pool implementation based on Erlang processes.
Types
Values
pub fn checkout(
pool: Pool,
) -> Result(connection.Connection, connection.DbError)
Get Connection (Unsafe)
Gets a connection from the pool without automatic return.
You MUST call release when done, or connections will leak.
Prefer with_connection for safety.
pub fn get_connection(
pool: Pool,
handler: fn(connection.Connection) -> response.Response(
wisp.Body,
),
) -> response.Response(wisp.Body)
Get Connection
Borrows a connection from the pool, executes a function, and returns the connection to the pool. Returns a Response, making it ideal for use in controller functions.
On pool error, returns wisp.internal_server_error().
Example:
pub fn show(req: Request, ctx: Context) -> Response {
use conn <- pool.get_connection(ctx.db.pool)
use user <- user_repository.find(conn, 1)
wisp.html_response("Hello " <> user.name, 200)
}
pub fn get_connection_or(
pool: Pool,
f: fn(connection.Connection) -> Result(a, connection.DbError),
) -> Result(a, connection.DbError)
Get Connection (Result)
Borrows a connection from the pool, executes a function, and returns the connection to the pool. Returns a Result, useful for operations that need error handling like transactions.
Example:
use conn <- pool.get_connection_or(pool)
query.execute(conn, "SELECT 1", [])
pub fn release(pool: Pool, conn: connection.Connection) -> Nil
Release Connection
Returns a connection to the pool. Only needed if you used
checkout directly instead of with_connection.
pub fn start(
config: connection.Config,
) -> Result(Pool, connection.DbError)
Start Pool
Starts a connection pool with the given configuration. For Postgres, this creates a named connection pool. For SQLite, this creates a pool of connections managed by an Erlang process.
Example:
let config = connection.sqlite_config("data.db", pool_size: 5)
let assert Ok(pool) = pool.start(config)