ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

DatabaseConnectingMigrationsSeveral instancesSQLxSeaORMDieselMongoDBRedis

Operating

Reference

Database

Diesel

diesel-async pools for Postgres, MySQL and SQLite, and how a synchronous driver runs beside an async runtime.

ulo-db-diesel binds a deadpool Pool of diesel-async connections. It needs Rust 1.89.

Cargo.toml
[dependencies]
ulo-db-diesel = { version = "=0.1.0-alpha.3", features = ["sqlite"] }
diesel = { version = "2", features = ["sqlite"] }
diesel-async = { version = "0.9", features = ["sqlite"] }

There is one feature per engine, postgres, mysql and sqlite, and none is on by default. The clients are PgPool, MySqlPool and SqlitePool, exported by the crate:

examples/37-db-diesel/src/lib.rs
use ulo_db_diesel::{DieselModule, Sqlite, SqlitePool};

m.import(DieselModule::<Sqlite>::from_config(&self.config, "database"));
m.provide::<Counter>();

A provider takes the pool and checks a connection out for diesel-async's RunQueryDsl:

examples/37-db-diesel/src/lib.rs
use diesel::dsl::sql;
use diesel::sql_types::BigInt;
use diesel_async::RunQueryDsl;
use ulo::{BoxError, Dep, injectable};

#[injectable]
pub struct Counter {
    pool: Dep<SqlitePool>,
}

impl Counter {
    pub async fn count_to(&self, n: i64) -> Result<i64, BoxError> {
        let mut conn = self.pool.get().await?;
        let query = format!("(with recursive c(x) as (select 1 union all select x + 1 from c where x < {n}) select count(*) from c)");
        Ok(diesel::select(sql::<BigInt>(&query)).get_result(&mut *conn).await?)
    }
}

Options

KeyDefaultMeaning
urlrequiredpostgres:// or postgresql://, mysql://, or for SQLite a path, :memory:, a file: URI or sqlite://<path>. A Secret.
max_sizedeadpool's defaultThe pool's largest size. Zero is refused.
wait_timeout_secsnoneHow long a caller waits for a connection while the pool is at its size. Unset, the caller waits until one is returned.

A Postgres URL is validated with tokio-postgres's parser and a MySQL URL with mysql_async's, the parsers diesel-async connects through.

A synchronous driver beside an async runtime

diesel-async's Postgres and MySQL connections are async from end to end, so no query blocks a worker. SQLite is the case where the runtime matters: its connection blocks its thread for as long as a query runs. The SQLite store therefore runs each query on the blocking pool of the runtime the application was given. The runtime's own threads keep polling other tasks meanwhile.

The store passes that runtime to diesel-async explicitly. The runtime check proves the application's runtime is tokio. It does not prove that the thread polling a query has tokio's context, and diesel-async's default builds a hidden runtime of its own where it finds none. The store's Given is a SpawnBlocking over the handle of the runtime the application was given, so no runtime is found ambiently. Migrations run on the same blocking pool.

examples/37-db-diesel/tests/off_the_worker.rs measures it: the app and a ticker share one thread, and during a query of a few hundred milliseconds the ticker's longest gap stays under a quarter of the query's duration. EX_REPORT_TICKS=1 prints the measurement.

cargo test -p ex-37-db-diesel
PORT=7000 cargo run -p ex-37-db-diesel
curl http://127.0.0.1:7000/count/1000000

The example reads APP_DATABASE__URL for a file and defaults to :memory: through a Values layer under the environment. It links the system libsqlite3.

Migrations

DieselMigrations::new(MIGRATIONS), with MIGRATIONS a const holding embed_migrations!(), runs diesel_migrations, which takes no lock. It runs under ulo-db's lock: pg_advisory_lock and GET_LOCK on a session of their own, and for a SQLite file an OS lock on <file>.ulo-migrate.lock beside it, which is left in place.

use diesel_migrations::EmbeddedMigrations;
use ulo_db_diesel::{DieselMigrations, DieselModule, Postgres};

const MIGRATIONS: EmbeddedMigrations = diesel_migrations::embed_migrations!();

m.import(DieselModule::<Postgres>::from_config(&config, "database")
    .migrate(DieselMigrations::new(MIGRATIONS)));

Errors

diesel-async's errors lose the SQLSTATE, so wrong credentials and an unknown database arrive alike as DatabaseError(Unknown, message). The store matches the message against fragments of the servers' English refusals to call a failure permanent. A server whose messages are not in English has bad credentials retried to the connect bound.

No test exercises a TLS connection through this store.

SeaORM

SeaORM's DatabaseConnection as a store, with the SQLite pool and migration specifics.

MongoDB

The MongoDB client as a store, and how the URI scheme decides whether the module can start lazily.

On this page

OptionsA synchronous driver beside an async runtimeMigrationsErrors