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 and DB_POOL_SIZE from the environment.
For PostgreSQL, uses DB_URL if set, otherwise uses individual parameters: DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD.
For SQLite, DB_DATABASE is preferred but DB_PATH is supported for backward compatibility.
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)