Database
A database is a module that reads its options from configuration, connects under a bound, contributes a health check and closes with the application.
Each store crate, one per database library, supplies one module. Import it with the options it reads from a configuration section, and inject the library's own client by type. Ulo does not wrap the driver, so the query API is the one the driver's documentation describes.
ulo-db implements the policy every store shares, written once: the connect and retry loop, the health check, the migration lock and the close. A store crate supplies the pieces that name a driver.
| Store | Module | Client you inject | URL schemes |
|---|---|---|---|
| SQLx | SqlxModule::<Postgres>, <MySql>, <Sqlite> | sqlx::PgPool, MySqlPool, SqlitePool | postgres://, mysql://, sqlite: |
| SeaORM | SeaOrmModule | DatabaseConnection | as SQLx |
| Diesel | DieselModule::<Postgres>, <MySql>, <Sqlite> | a deadpool PgPool, MySqlPool, SqlitePool | postgres://, mysql://, a SQLite path |
| MongoDB | MongoModule | mongodb::Client | mongodb://, mongodb+srv:// |
| Redis | RedisModule | ConnectionManager | redis://, rediss:// |
The Rust Prisma client is archived, so no Prisma module ships and a generated client registers by hand like any other, as in A client as a provider.
Every store crate needs the application to run on tokio. An application on another runtime fails connect with ulo_db::UnsupportedRuntime, wrapped in ulo::Permanent, naming the module and the runtime it was given.
One database
This is examples/35-db-sqlx. The module reads the database section, applies the migrations in migrations/, and binds SQLx's own PgPool:
use ulo::{Module, ModuleDef, ModuleIdentity, controller};
use ulo_db_sqlx::sqlx::{self, PgPool};
use ulo_db_sqlx::{Postgres, SqlxModule};
use ulo_health::HealthModule;
use ulo_health_http::HealthHttp;
fn register(&self, m: &mut ModuleDef<'_>) {
let store = SqlxModule::<Postgres>::from_config(&self.config, "database");
m.import(store.migrate(sqlx::migrate!("./migrations")));
m.import(HealthModule::new());
m.import(HealthHttp::new().detail(true));
m.provide::<Notes>();
m.controller::<NotesController>();
}A provider takes the pool as a dependency, and queries go through the library:
use ulo::{BoxError, Dep, injectable};
#[injectable]
pub struct Notes {
pool: Dep<PgPool>,
}
impl Notes {
pub async fn all(&self) -> Result<Vec<Note>, sqlx::Error> {
let rows: Vec<(i64, String)> = sqlx::query_as("select id, title from notes order by id").fetch_all(&*self.pool).await?;
Ok(rows.into_iter().map(|(id, title)| Note { id, title }).collect())
}
}The options come from the configuration the application loaded in main. The example uses the environment alone:
use ulo_config::{Config, Env, Values};
pub fn config(env: Env, explicit: Values) -> Config {
Config::builder().source(env.prefix("APP_").separator("__")).source(explicit).load()
}APP_DATABASE__URL=postgres://postgres:pw@127.0.0.1/postgres APP_DATABASE__MAX_CONNECTIONS=5 cargo run -p ex-35-db-sqlxA module built in code, without a Config, uses from_options(options) instead of from_config(&config, path).
What a store module does
| Phase | What the module does |
|---|---|
wire (see Application phases) | Validates its options and records every problem, registers the URL and the URL's password as secrets, contributes its health check. |
connect | Checks the runtime's name, creates the client on the app's runtime, pings under the retry policy, runs migrations under a lock when asked. |
listen, drain | Nothing. In-flight requests keep using the client. |
| destroy | Closes the client, after every transport has drained. |
A URL of another engine, or a missing one, is refused by wire() before any connection is tried, and the report prints no part of the URL. The URL is a Secret, and its Debug is redacted.
Health
Each store contributes a check that pings the database, named after the store and the section: postgres@database for a module read from the database section, and postgres for one built with from_options. See Health checks. .without_health_check() leaves the check out.
Closing
The pool closes in the module's destroy hook, which runs after the transports have drained. A query that was in flight when the drain began completes. The wait for connections to return is bounded by the destroy hook's timeout.