Databases
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"] }
| Feature | Module | Notes |
|---|---|---|
tokio-postgres | vld_data::postgres_types | postgres-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>— aJSON/JSONBcolumn.new(value)validatesT(serialized) againstS;to_sqlsends it as JSON;from_sqlvalidates the stored JSON againstS, then deserializes it intoT.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 avaluefield);new,new_unchecked,Deref.VldPgError—Validation,Serialization; a failed read returns it boxed fromFromSql(err.downcast_ref::<VldPgError>()).
Gotchas
- Reads are validated too: a stored value that breaks the schema makes
Row::try_getfail (andRow::getpanic). Use plainserde_json::Value/i64columns for data you want to load unchecked. Validatedkeeps the originalT, not the schema's parsed output: defaults and transforms ofSare checked but not applied.VldIntisi64, so it binds toINT8(BIGINT) only; a stored floatNaNis rejected withnot_finite.