glimr/db/db


Database Utilities

High-level database utilities including transaction support with automatic retry on deadlock.

Values

pub fn load_config() -> connection.Config

Load Config

Builds database configuration from environment variables. Reads DB_DRIVER (postgres or sqlite), DB_URL or DB_PATH, and DB_POOL_SIZE from the environment.

pub fn transaction(
  pool: pool.Pool,
  retries: Int,
  callback: fn(connection.Connection) -> Result(
    a,
    connection.DbError,
  ),
) -> Result(a, connection.DbError)

Transaction

Executes a function within a database transaction. The connection is automatically checked out from the pool, and the transaction is committed on success or rolled back on error.

The retries parameter controls retry behavior for deadlocks:

  • 0 = no retries (try once, fail on error)
  • 3 = retry up to 3 times on deadlock (4 total attempts)

Example:

db.transaction(pool, fn(conn) {
  use _ <- account_repository.debit(conn, from_id, amount)
  use _ <- account_repository.credit(conn, to_id, amount)
  Ok(Nil)
}, 3)
Search Document