Databases
vld-surrealdb validates documents with vld schemas around SurrealDB calls. It has no surrealdb dependency: everything goes through serde, so it works with any SDK version.
Install
Cargo.toml
[dependencies]
vld = "0.5"
vld-surrealdb = "0.5"
No features. MSRV: 1.85 (see MSRV).
Example
use vld_surrealdb::prelude::*;
vld::schema! {
#[derive(Debug)]
pub struct PersonSchema {
pub name: String => vld::string().min(1).max(100),
pub email: String => vld::string().email(),
pub age: i64 => vld::number().int().min(0).max(150),
}
}
#[derive(serde::Serialize)]
struct Person { name: String, email: String, age: i64 }
let person = Person { name: "Alice".into(), email: "alice@example.com".into(), age: 30 };
// Before db.create("person").content(person):
validate_content::<PersonSchema, _>(&person).unwrap();
// Inline checks for a MERGE:
let name = "Bob";
let email = "bob@example.com";
validate_fields! {
name => vld::string().min(1),
email => vld::string().email(),
}
.unwrap();
// Serializable error body for an API response:
let bad = Person { name: "".into(), email: "x".into(), age: 200 };
if let Err(e) = validate_content::<PersonSchema, _>(&bad) {
let body = VldSurrealResponse::from_error(&e).to_json();
assert_eq!(body["error"], "Validation failed");
}
API
validate_content::<S, T>(&value)— serialize and validate before create / insert / update.validate_records::<S, T>(&rows)— validate a batch; the error is(index, VldSurrealError)of the first invalid row.validate_json::<S>(&json)— validate a raw JSON value against a schema type.validate_value(&schema, &json)— validate against a schema instance (vld::string().min(1)).validate_fields! { name => schema, ... }— validate local variables inline; issues are prefixed with the variable name.Validated<S, T>— validated wrapper (new,inner,into_inner,Deref,Serialize).VldText<S>,VldInt<S>,VldFloat<S>,VldBool<S>— validated scalars (the schema must have avaluefield); validated on construction and on deserialization.VldSurrealError—Validation(VldError)orSerialization(String).VldSurrealResponse { error, fields: Vec<FieldError> }—from_error,from_vld_error,to_json.FieldError { field, message }— re-exported fromvld-integration-common.
Gotchas
- Issue paths have no leading dot:
user.email,items[0]. validate_fields!stops at the first field that cannot be serialized and returnsVldSurrealError::Serialization.- Keys the schema does not declare (such as a record
idin select results) are ignored byschema!structs.