Databases

tokio-postgres

ToSql / FromSql column types validated when they are built and when they are read, for tokio-postgres and postgres.

vld_data::postgres_types gives tokio-postgres (and the synchronous postgres crate) column types that implement ToSql / FromSql and are validated against a vld schema when they are built and when a row is read.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["tokio-postgres"] }
tokio-postgres = { version = "0.7", features = ["with-serde_json-1"] }
FeatureModuleNotes
tokio-postgresvld_data::postgres_typespostgres-types 0.2 (used by tokio-postgres 0.7 and postgres 0.19)

Example

use vld_data::postgres_types::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct ProfileSchema {
        pub nickname: String => vld::string().min(2),
    }
}

vld::schema! {
    #[derive(Debug)]
    pub struct Score {
        pub value: i64 => vld::number().int().min(0).max(100),
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Profile { nickname: String }

async fn run(client: &tokio_postgres::Client) -> Result<(), Box<dyn std::error::Error>> {
    let profile = Validated::<ProfileSchema, _>::new(Profile { nickname: "ada".into() })?;
    let score = VldInt::<Score>::new(42)?;
    client
        .execute("INSERT INTO users (profile, score) VALUES ($1, $2)", &[&profile, &score])
        .await?;

    let row = client.query_one("SELECT profile, score FROM users", &[]).await?;
    let profile: Validated<ProfileSchema, Profile> = row.try_get("profile")?; // validated
    let score: VldInt<Score> = row.try_get("score")?;                         // validated
    println!("{} {}", profile.nickname, *score);
    Ok(())
}

API

  • Validated<S, T> — a JSON / JSONB column. new(value) validates T (serialized) against S; to_sql sends it as JSON; from_sql validates the stored JSON against S, then deserializes it into T. inner(), into_inner(), Deref.
  • VldText<S> (TEXT, VARCHAR, …), VldInt<S> (INT8), VldFloat<S> (FLOAT8), VldBool<S> (BOOL) — scalars checked as {"value": v} (the schema needs a value field); new, new_unchecked, Deref.
  • VldPgError — Validation, Serialization; a failed read returns it boxed from FromSql (err.downcast_ref::<VldPgError>()).

Gotchas

  • Reads are validated too: a stored value that breaks the schema makes Row::try_get fail (and Row::get panic). Use plain serde_json::Value / i64 columns for data you want to load unchecked.
  • Validated keeps the original T, not the schema's parsed output: defaults and transforms of S are checked but not applied.
  • VldInt is i64, so it binds to INT8 (BIGINT) only; a stored float NaN is rejected with not_finite.