ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

DatabaseConnectingMigrationsSeveral instancesSQLxSeaORMDieselMongoDBRedis

Operating

Reference

Database

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.

StoreModuleClient you injectURL schemes
SQLxSqlxModule::<Postgres>, <MySql>, <Sqlite>sqlx::PgPool, MySqlPool, SqlitePoolpostgres://, mysql://, sqlite:
SeaORMSeaOrmModuleDatabaseConnectionas SQLx
DieselDieselModule::<Postgres>, <MySql>, <Sqlite>a deadpool PgPool, MySqlPool, SqlitePoolpostgres://, mysql://, a SQLite path
MongoDBMongoModulemongodb::Clientmongodb://, mongodb+srv://
RedisRedisModuleConnectionManagerredis://, 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:

examples/35-db-sqlx/src/lib.rs
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:

examples/35-db-sqlx/src/lib.rs
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:

examples/35-db-sqlx/src/lib.rs
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-sqlx

A module built in code, without a Config, uses from_options(options) instead of from_config(&config, path).

What a store module does

PhaseWhat 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.
connectChecks 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, drainNothing. In-flight requests keep using the client.
destroyCloses 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.

Connecting

The connect bound, retries, permanent failures and lazy modules.

Migrations

Running migrations at startup under a lock shared by replicas.

Several instances

Two databases of one kind, told apart by qualifiers.

Engines

What async-graphql and juniper share under the Engine trait, and the places they differ.

Connecting

How a store module waits for its database, which failures stop it at once, and when to start without one.

On this page

One databaseWhat a store module doesHealthClosing