Skip to main content
Version: 0.8.0

Schema Options

Grouped, cross-field options attach to an anonymous const _: () = (); item directly inside the schema module -- not chained onto the #[ivo_schema(...)] call itself. Use them when a rule or side effect involves more than one field, or when you want to react to the entity as a whole. Multiple option attributes may be stacked on one const, or spread across several.

ignore​

Skip processing for a group of lax or virtual fields together, based on a shared condition. Requires at least two fields, and applies to both create and update.

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(Contact, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod contact_schema {
struct Fields {
#[lax(String::new())]
pub email: String,

#[lax(String::new())]
pub phone: String,
}

// a placeholder email drops both contact details
#[ignore(["email", "phone"], |ctx, _opts| {
ctx.input().email.as_deref() == Some("skip")
})]
const _: () = ();
}

fn main() {
use contact_schema::{ContactModel, PartialContact};

let contact = |email: &str| PartialContact { email: Some(email.into()), phone: Some("123".into()) };

let ignored = ContactModel.create(contact("skip")).unwrap();
println!("{:?}", ignored); // Contact { email: "", phone: "" }

let kept = ContactModel.create(contact("ada@example.com")).unwrap();
println!("{:?}", kept); // Contact { email: "ada@example.com", phone: "123" }
}

See lax_with_ignore.rs and field-level #[ignore] on virtual fields (Virtual Fields, in the Fields section of the sidebar).

ignore_update​

Same idea as ignore, but evaluated during updates only. #[ignore_update([...], handler)] requires at least two fields; to ignore the entire entity on update, omit the array and use the bare #[ignore_update(handler)] entity-level form instead.

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(User, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod user_schema {
struct Fields {
#[lax(String::new())]
pub email: String,

#[lax(String::new())]
pub phone: String,

#[lax(false)]
pub verified: bool,
}

// contact details can only change once the account is verified
#[ignore_update(["email", "phone"], |ctx, _opts| ctx.values().verified != Some(true))]
const _: () = ();
}

fn main() {
use user_schema::{PartialUser, User, UserModel};

let changes = || PartialUser { email: Some("new@example.com".into()), phone: None, verified: None };

let unverified = User { email: "old@example.com".into(), phone: String::new(), verified: false };
let errors = UserModel.update(unverified.clone(), changes()).unwrap_err();
println!("{:?}", errors); // None

let verified = User { verified: true, ..unverified };
let updated = UserModel.update(verified, changes()).unwrap();
println!("{:?}", updated); // PartialUser { email: Some("new@example.com"), phone: None, verified: None }
}

See lax_with_ignore_update.rs.

required​

Enforces that at least one of the listed lax/virtual fields is provided. The handler runs only when none of the listed fields were provided, and returns Option<{InputName}Errors> -- Some merges per-field errors into the payload, None means the requirement doesn't apply. Requires at least two fields. Commonly used for "provide email or phone" style rules.

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(Contact, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod contact_schema {
struct Fields {
#[lax(None)]
pub email: Option<String>,

#[lax(None)]
pub phone_number: Option<String>,
}

// runs only when none of the fields is provided
#[required(["email", "phone_number"], |_ctx, _opts| {
println!("(the required handler ran)");
let reason = "provide either an email or a phone number";
let mut errors = ContactErrors::new();
errors.set_email(reason, None);
errors.set_phone_number(reason, None);
Some(errors)
})]
const _: () = ();
}

fn main() {
use contact_schema::{ContactModel, PartialContact};

let errors = ContactModel
.create(PartialContact { email: None, phone_number: None })
.unwrap_err(); // (the required handler ran)
println!("{:?}", errors.get("email").unwrap().reason); // "provide either an email or a phone number"
println!("{:?}", errors.get("phone_number").unwrap().reason); // "provide either an email or a phone number"

let contact = ContactModel
.create(PartialContact { email: Some(Some("ada@example.com".into())), phone_number: None })
.unwrap();
println!("{:?}", contact); // Contact { email: Some("ada@example.com"), phone_number: None }
}

DataInputErrors is generated automatically alongside DataInput/PartialDataInput. See the same pattern in main_demo/src/domain.rs.

post_validate​

Cross-field validation that runs after every individual field's re_validate. Can also return updated values for the group's own fields (pre_validate runs first and can feed updated values into the main validator). Requires at least two fields, from lax, required or virtual fields.

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(Signup, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod signup_schema {
struct Fields {
#[lax(String::new())]
pub password: String,

#[lax(String::new())]
pub confirm_password: String,
}

#[post_validate(["password", "confirm_password"], |ctx, _opts| {
let input = ctx.input();

if input.password != input.confirm_password {
let mut errors = SignupErrors::new();
errors.set_confirm_password("passwords do not match", None);
return Err(errors);
}

Ok(None)
})]
const _: () = ();
}

fn main() {
use signup_schema::{PartialSignup, SignupModel};

let signup = |password: &str, confirm: &str| PartialSignup {
password: Some(password.into()),
confirm_password: Some(confirm.into()),
};

let errors = SignupModel.create(signup("secret", "wrong")).unwrap_err();
println!("{:?}", errors.get("confirm_password").unwrap().reason); // "passwords do not match"

let signup = SignupModel.create(signup("secret", "secret")).unwrap();
println!("{:?}", signup); // Signup { password: "secret", confirm_password: "secret" }
}

See the cross-field validation in main_demo/src/domain.rs.

Returning values​

Ok(Some(...)) returns updated values for the group's own fields:

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(Range, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod range_schema {
struct Fields {
#[lax(0)]
pub min: i32,

#[lax(0)]
pub max: i32,
}

// swaps reversed bounds instead of rejecting them
#[post_validate(["min", "max"], |ctx, _opts| {
let (min, max) = (ctx.values().min.unwrap(), ctx.values().max.unwrap());

if min > max {
return Ok(Some(PartialRange { min: Some(max), max: Some(min) }));
}

Ok(None)
})]
const _: () = ();
}

fn main() {
use range_schema::{PartialRange, RangeModel};

let range = RangeModel.create(PartialRange { min: Some(10), max: Some(2) }).unwrap();
println!("{:?}", range); // Range { min: 2, max: 10 }
}

on_success​

Register a handler that runs after a successful create or update, via the trigger returned as the third element of the Ok tuple (see Life Cycles - Triggering handlers). The bare, arrayless form fires on every success; #[on_success([...], handler)] requires at least one field and fires when at least one of the listed fields is part of the success payload.

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(Data, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod hooks_schema {
struct Fields {
#[lax(0)]
pub a: i32,

#[lax(0)]
pub b: i32,

#[lax(0)]
pub c: i32,
}

#[on_success(|_ctx, _opts| {
println!("(entity created or updated)");
})]
const _: () = ();

// only when `a` or `b` is involved
#[on_success(["a", "b"], |_ctx, _opts| {
println!("(a and/or b changed)");
})]
const _: () = ();
}

fn main() {
use hooks_schema::{Data, DataModel, PartialData};

let data = Data { a: 1, b: 2, c: 3 };

// `c` isn't in the group: only the entity-level handler runs
let (_, handle_success) = DataModel
.update(data.clone(), PartialData { a: None, b: None, c: Some(4) })
.ok()
.unwrap();
handle_success(); // (entity created or updated)

let (_, handle_success) = DataModel
.update(data, PartialData { a: Some(10), b: None, c: None })
.ok()
.unwrap();
handle_success(); // (entity created or updated)
// (a and/or b changed)
}

See the runnable option_on_success.rs example for more detail, including dependent and virtual fields.

on_delete​

Register one or more handlers that run when a schema's generated delete method is invoked, in addition to any per-field #[on_delete] handlers -- see the Life Cycles page (onDelete) in the sidebar.

main.rs
use ivo::ivo_schema;

#[ivo_schema(input(Data, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod delete_schema {
struct Fields {
#[lax(0)]
pub a: i32,
}

#[on_delete(|data, _opts| {
println!("(deleting the entity with a = {})", data.a);
})]
const _: () = ();
}

fn main() {
delete_schema::DataModel.delete(&delete_schema::Data { a: 7 }); // (deleting the entity with a = 7)
}

timestamps​

The shared, synchronous resolver for #[created_at]/#[updated_at]/#[optional_updated_at] fields -- see the Timestamps page in the Fields section of the sidebar for the full picture.

#[timestamps(|| chrono::Utc::now())]
const _: () = ();

Accepts either a zero-arg closure or a bare function path (#[timestamps(chrono::Utc::now)]).

Custom context options​

ctx_options(YourType) in the macro call threads a value of your own type (dependency injection, caching, request-scoped data, ...) through every handler in a create/update call, wrapped in a read/write lock so concurrent handlers can share and mutate it safely. Async handlers use opts.read().await/opts.write().await; sync handlers use opts.read_sync()/opts.write_sync().

main.rs
use ivo::ivo_schema;

#[derive(Debug, Clone, Default)]
pub struct AppCtxOptions {
pub calls: u32,
}

#[ivo_schema(
input(DataInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
ctx_options(AppCtxOptions)
)]
mod ctx_options_schema {
use super::AppCtxOptions;

struct Fields {
#[required]
#[validate(|v: &String, _, opts| {
opts.write_sync().calls += 1;
Ok(None)
})]
pub name: String,
}
}

fn main() {
let (created, ctx_options) = ctx_options_schema::DataInputModel
.create(
ctx_options_schema::PartialDataInput {
name: Some("jane".into()),
},
AppCtxOptions::default(),
)
.unwrap();

println!("name={:?} calls={}", created.name, ctx_options.calls); // name="jane" calls=1
}

The ctx_options returned alongside data is the plain, final value -- no lock or accessor needed; opts.write_sync()/opts.read_sync() (and their .awaiting counterparts, opts.write()/opts.read()) are only for handlers, which run concurrently with each other during the call and so see the value through a read/write lock. A schema that declares no ctx_options(...) takes no such argument and returns none, as in every other example on this page; its handlers receive () options. See main_demo/src/domain.rs for a complete, realistic example (dependency lookups, uniqueness checks, and mutation across several handlers in the same call).

Custom error payloads with IvoErrorSanitizer​

By default ivo returns errors as HashMap<&'static str, FieldError<()>>. Change the shape of the error payload by implementing IvoErrorSanitizer and passing it via error_sanitizer(...):

main.rs
use std::collections::HashMap;
use ivo::{ivo_schema, IvoErrorPayload, IvoErrorSanitizer};

struct MyErrorSanitizer;

impl IvoErrorSanitizer<()> for MyErrorSanitizer {
type Metadata = Vec<String>;
type Payload = HashMap<String, Vec<String>>;

fn sanitize(payload: IvoErrorPayload<Self::Metadata>, _opts: &()) -> Self::Payload {
payload
.into_iter()
.map(|(name, err)| {
let mut messages = vec![err.reason.into_owned()];
if let Some(meta) = err.metadata {
messages.extend(meta);
}
(name.to_string(), messages)
})
.collect()
}
}

#[ivo_schema(
input(DataInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
error_sanitizer(MyErrorSanitizer)
)]
mod sanitized_schema {
use super::MyErrorSanitizer;

struct Fields {
#[required]
#[validate(|v: &String, _, _| {
if v.len() < 3 {
return Err(("too short".into(), Some(vec!["min length is 3".into()])));
}
Ok(None)
})]
pub username: String,
}
}

fn main() {
let err = sanitized_schema::DataInputModel
.create(sanitized_schema::PartialDataInput {
username: Some("ab".into()),
})
.unwrap_err();

println!("{:?}", err); // {"username": ["too short", "min length is 3"]}
}

See the full example, including a custom ctx_options type, in tests/extras/error_sanitizer.rs.

API reference​

For the exhaustive list of grouped-option signatures and constraints, see:

  • docs.rs/crate/ivo — hosted rustdoc for the published crate.
  • Local rustdoc — run cargo doc --no-deps --open from the rs/ directory to browse the same generated reference locally.