validator
ModuleValidators: documents against their collection (structure), queries
(queries, query), attribute and index definitions, keys,
permissions and roles, and the authorization check of a permission
list against the current roles.
State
Contents
32 submodules.
validator::attribute
Own page[Attribute]: attribute definitions before they are created.
use utopia_database::validator::attribute::Attribute;pub struct AttributeAn attribute definition the collection can take: a new key (in the metadata and, with schema attributes, in the table), the filters and format its type needs, within the attribute count and row width limits, a supported type of a valid size, and a default of its type.
use utopia_database::Document;
use utopia_database::validator::attribute::{Attribute, AttributeOptions};
use utopia_database::value::{Value, string};
let validator = Attribute::new(&[], &[], AttributeOptions { max_string_length: 1000, ..Default::default() });
let title = Document::from_pairs([("$id", string("title")), ("type", string("string")), ("size", Value::Int(2000))]).unwrap();
assert_eq!(validator.check(&title).unwrap_err().message(), "Max size allowed for string is: 1,000");use utopia_database::validator::attribute::AttributeOptions;pub struct AttributeOptionsUndocumented.
pub type Filter = Box<dyn Fn(&str) -> String + Send + Sync>Undocumented.
pub type Measure = Box<dyn Fn(&Document) -> Result<i64> + Send + Sync>Undocumented.
use utopia_database::Authorization;pub struct AuthorizationThe current roles, and whether authorization is enforced.
use utopia_database::validator::authorization::{Authorization, Input};
let auth = Authorization::new();
auth.add_role("user:1");
assert!(auth.is_valid(&Input::new("read", vec!["user:1".into()])));
assert!(!auth.is_valid(&Input::new("read", vec!["user:2".into()])));
assert_eq!(auth.description(), "Missing \"read\" permission for role \"user:2\". Only \"[\"any\",\"user:1\"]\" scopes are allowed and \"[\"user:2\"]\" was given.");Default, Validator.use utopia_database::validator::authorization::Input;pub struct InputThe action and permissions an Authorization checks.
validator::big_int
Own pageuse utopia_database::validator::big_int::BigInt;pub struct BigIntUndocumented.
use utopia_database::validator::big_int::BigInt;
use utopia_database::value::{Value, string};
let unsigned = BigInt::new(false, true);
assert!(unsigned.is_valid(&string("18446744073709551615")));
assert!(!unsigned.is_valid(&Value::Int(-1)));
assert_eq!(BigInt::format_integer_string("-1234567"), "-1,234,567");pub const SIGNED_MAX: &str = "9223372036854775807"BigInt::SIGNED_MAX.
pub const SIGNED_MIN: &str = "-9223372036854775808"BigInt::SIGNED_MIN.
pub const UNSIGNED_MAX: &str = "18446744073709551615"BigInt::UNSIGNED_MAX.
validator::byte_length
Own page[ByteLength]: strings of bounded byte length.
use utopia_database::validator::byte_length::ByteLength;pub struct ByteLengthA string of at most max bytes (0: no limit).
use utopia_database::validator::byte_length::ByteLength;
use utopia_database::value::string;
assert!(ByteLength::new(3).is_valid(&string("abc")));
assert!(!ByteLength::new(3).is_valid(&string("héé")));validator::datetime
Own page[Datetime]: date strings within a range, optionally in the future and
at a precision.
use utopia_database::validator::datetime::Datetime;pub struct DatetimeUndocumented.
use utopia_database::validator::datetime::Datetime;
use utopia_database::value::string;
let validator = Datetime::default();
assert!(validator.is_valid(&string("2024-01-01 10:00:00")));
assert!(!validator.is_valid(&string("not a date")));
assert_eq!(validator.description(), "Value must be valid date between 0000-01-01 00:00:00 and 9999-12-31 00:00:00.");Default.use utopia_database::validator::datetime::Precision;pub enum PrecisionThe finest unit a date may set (Datetime).
use utopia_database::validator::datetime::default_max;pub fn default_max() -> DateTimeThe default maximum date.
use utopia_database::validator::datetime::default_min;pub fn default_min() -> DateTimeThe default minimum date.
validator::index
Own page[Index]: index definitions against a collection's attributes and the
adapter's capabilities.
use utopia_database::validator::index::Index;pub struct IndexAn index definition: a known type the adapter supports, on existing
attributes (no duplicates), with lengths, orders and attribute types
that suit its type, and not clashing with the collection's other
indexes (a second full-text or TTL index, an identical index).
use utopia_database::Document;
use utopia_database::validator::index::{Index, IndexSupport};
use utopia_database::value::{Value, list, string};
let title = Document::from_pairs([("$id", string("title")), ("type", string("string")), ("size", Value::Int(255))]).unwrap();
let validator = Index::new(&[title], vec![], 768, vec![], IndexSupport::default());
let index = Document::from_pairs([("$id", string("idx")), ("type", string("key")), ("attributes", list([string("title")]))]).unwrap();
assert!(validator.check(&index));
let missing = Document::from_pairs([("$id", string("idx")), ("type", string("key")), ("attributes", list([string("name")]))]).unwrap();
assert!(!validator.check(&missing));
assert_eq!(validator.description(), "Invalid index attribute \"name\" not found");use utopia_database::validator::index::IndexSupport;pub struct IndexSupportUndocumented.
Default.validator::index_dependency
Own page[IndexDependency]: whether an attribute can be deleted or renamed
while indexes use it.
use utopia_database::validator::index_dependency::IndexDependency;pub struct IndexDependencyAn attribute that no index uses, when the adapter indexes array
attributes through casts (cast_index_support) and the attribute is an
array; any attribute otherwise.
use utopia_database::Document;
use utopia_database::validator::index_dependency::IndexDependency;
use utopia_database::value::{Value, list, string};
let index = Document::from_pairs([("attributes", list([string("tags")]))]).unwrap();
let validator = IndexDependency::new(vec![index], true);
let tags = Document::from_pairs([("key", string("tags")), ("array", Value::Bool(true))]).unwrap();
assert!(!validator.check(&tags));validator::indexed_queries
Own page[IndexedQueries]: query lists that also need indexes (full-text
searches) and use at most one vector query.
use utopia_database::validator::indexed_queries::IndexedQueries;pub struct IndexedQueriesA Queries list whose search and notSearch filters each have a
full-text index on exactly their attribute, with at most one vector
query (nested ones included).
validator::key
Own page[Key]: attribute, index and collection keys.
use utopia_database::validator::key::Key;pub struct KeyA key: 1 to max_length characters among a-z, A-Z, 0-9, .,
- and _, not starting with ., - or _. With allow_internal,
the internal keys $id, $createdAt and $updatedAt are keys too.
use utopia_database::validator::key::Key;
use utopia_database::value::string;
let key = Key::default();
assert!(key.is_valid(&string("movie_1")));
assert!(!key.is_valid(&string("_movie")));
assert!(!key.is_valid(&string("$id")));
assert!(Key::new(true, 36).is_valid(&string("$id")));Default.validator::label
Own page[Label]: user labels.
use utopia_database::validator::label::Label;pub struct LabelA label: a Key made only of a-z, A-Z and 0-9.
use utopia_database::validator::label::Label;
use utopia_database::value::string;
assert!(Label::default().is_valid(&string("vip2")));
assert!(!Label::default().is_valid(&string("v.i.p")));Default.validator::object
Own page[ObjectValidator]: values of object attributes.
use utopia_database::validator::object::ObjectValidator;pub struct ObjectValidatorAn object value: a JSON string, a stdClass, an associative (non-list)
array, or an empty value (null, false, 0, [], ...).
use utopia_database::validator::object::ObjectValidator;
use utopia_database::value::{list, string, Value};
assert!(ObjectValidator.is_valid(&string("{\"a\":1}")));
assert!(!ObjectValidator.is_valid(&list([Value::Int(1)])));validator::operator
Own page[Operator]: atomic update operators against the attributes they
update.
use utopia_database::Operator;pub struct OperatorAn operator valid for the attribute it updates: an existing attribute of a type the method applies to (numbers for arithmetic, arrays or many-side relationships for array methods, strings, booleans, dates), with well-formed values; with the current document, an integer result within 32-bit range, a string result within the attribute's size, and an insert index within the array.
use utopia_database::Document;
use utopia_database::operator::{Operator, OperatorMethod};
use utopia_database::validator::operator::Operator as OperatorValidator;
use utopia_database::value::{Value, list, string};
let count = Document::from_pairs([("$id", string("count")), ("key", string("count")), ("type", string("integer"))]).unwrap();
let collection = Document::from_pairs([("$id", string("c")), ("attributes", list([count.into()]))]).unwrap();
let validator = OperatorValidator::new(&collection, None);
assert!(validator.check(&Operator::new(OperatorMethod::Increment, "count", vec![Value::Int(1)])).unwrap());
assert!(!validator.check(&Operator::new(OperatorMethod::Toggle, "count", vec![])).unwrap());
assert_eq!(validator.description(), "Cannot apply toggle operator to non-boolean field 'count'");pub const ARRAY_FILTER_CONDITIONS: [&str; 8] = ["equal", "notEqual", "greaterThan", "greaterThanEqual", "lessThan", "lessThanEqual", "isNull", "isNotNull"]Operator::ARRAY_FILTER_CONDITIONS: the conditions of arrayFilter.
pub const MAX_ARRAY_OPERATOR_SIZE: usize = 10000Operator::MAX_ARRAY_OPERATOR_SIZE: the most items an array operator
may carry.
validator::partial_structure
Own page[PartialStructure]: partial documents (the attributes of an update)
against their collection.
use utopia_database::validator::partial_structure::PartialStructure;pub struct PartialStructureA Structure check of the attributes a document has: it need not
name its collection or carry required attributes, except internal
required ones it does carry.
validator::permissions
Own page[Permissions]: lists of permission strings.
use utopia_database::validator::permissions::Permissions;pub struct PermissionsA list of permission strings (read("any"), update("user:123"), ...),
at most length of them (0: no limit), each starting with one of the
allowed actions and granted to a well-formed role.
use utopia_database::validator::permissions::Permissions;
use utopia_database::value::{list, string};
let permissions = Permissions::default();
assert!(permissions.is_valid(&list([string("read(\"any\")")])));
assert!(!permissions.is_valid(&list([string("read(\"user\")")])));
assert_eq!(permissions.description(), "Role \"user\" must have an ID value.");Default.pub const PERMISSIONS: [&str; 5] = ["create", "read", "update", "delete", "write"][...Database::PERMISSIONS, Database::PERMISSION_WRITE]: the actions a
permission may grant, by default.
validator::queries
Own page[Queries]: lists of queries, each checked by the QueryValidator
of its kind; and the lists for one document (document) and for
document finds (documents).
use utopia_database::validator::queries::Queries;pub struct QueriesA list of queries: at most length of them (0: no limit), each parsed
and valid for every validator of its kind (and at least one), nested
queries included.
use utopia_database::query::{Method, Query};
use utopia_database::validator::queries::Queries;
use utopia_database::validator::query::limit::Limit;
let queries = Queries::new(vec![Box::new(Limit::default())], 0);
assert!(queries.check(&[Query::new(Method::Limit, "", vec![10.into()])]));
assert!(!queries.check(&[Query::new(Method::Offset, "", vec![10.into()])]));
assert_eq!(queries.description(), "Invalid query method: offset");validator::queries::document
Own page[Document]: the queries of a single-document read (selections only).
use utopia_database::Document;pub struct DocumentThe queries of a document read: select queries of the collection's
attributes (and $id, $createdAt, $updatedAt).
validator::queries::documents
Own page[Documents]: the queries of a document find.
use utopia_database::validator::queries::documents::Documents;pub struct DocumentsThe queries of a find: limits, offsets, cursors, filters, orders and
selections on the collection's attributes (and $id, $sequence,
$createdAt, $updatedAt), searches backed by full-text indexes.
use utopia_database::query::{Method, Query};
use utopia_database::validator::queries::documents::Documents;
use utopia_database::value::{Value, string};
let documents = Documents::new(&[], &[], "integer");
assert!(documents.check(&[Query::new(Method::Equal, "$id", vec![string("a")]), Query::new(Method::Limit, "", vec![Value::Int(10)])]));
assert!(!documents.check(&[Query::new(Method::Search, "$id", vec![string("a")])]));
assert_eq!(documents.description(), "Searching by attribute \"$id\" requires a fulltext index.");use utopia_database::validator::queries::documents::DocumentsOptions;pub struct DocumentsOptionsUndocumented.
Default.validator::query
Own pageValidators of one query by kind (Validator\Query\*): filters, cursors,
limits, offsets, orders and selections.
validator::query::base
Own page[QueryValidator]: the validator of one kind of query that
crate::validator::queries::Queries dispatches to, by MethodType.
use utopia_database::validator::query::base::MethodType;pub enum MethodTypeThe kind of query a QueryValidator validates.
use utopia_database::validator::query::base::QueryValidator;pub trait QueryValidator: Send + SyncA validator of one kind of query. Implement it to add a query
validator to a crate::validator::queries::Queries.
validator::query::cursor
Own page[Cursor]: cursorAfter and cursorBefore queries.
use utopia_database::validator::query::cursor::Cursor;pub struct CursorA cursor query whose value (a document id, or a document) is a valid
Uid of at most max_length characters.
use utopia_database::query::{Method, Query};
use utopia_database::validator::query::cursor::Cursor;
use utopia_database::value::string;
let cursor = Cursor::default();
assert!(cursor.check(&Query::new(Method::CursorAfter, "", vec![string("doc1")])));
assert!(!cursor.check(&Query::new(Method::CursorAfter, "", vec![string("_doc")])));Default.validator::query::filter
Own page[Filter]: filter queries (equal, contains, between, spatial,
vector, logical, ...).
use utopia_database::validator::query::filter::Filter;pub struct FilterA filter query on an attribute of the collection whose values suit the
attribute's type: at most max_values_count values, strings for
strings, integers in range for integers, dates between the allowed
dates, ... Logical queries (and, or, elemMatch) must nest filters.
use utopia_database::Document;
use utopia_database::query::{Method, Query};
use utopia_database::validator::query::filter::Filter;
use utopia_database::value::{Value, string};
let attributes = [Document::from_pairs([
("key", string("age")),
("type", string("integer")),
("array", Value::Bool(false)),
])
.unwrap()];
let filter = Filter::new(&attributes, "integer");
assert!(filter.check(&Query::new(Method::GreaterThan, "age", vec![Value::Int(18)])));
assert!(!filter.check(&Query::new(Method::GreaterThan, "age", vec![string("18")])));
assert_eq!(filter.description(), "Query value is invalid for attribute \"age\"");use utopia_database::validator::query::filter::FilterOptions;pub struct FilterOptionsUndocumented.
Default.validator::query::limit
Own page[Limit]: limit queries.
use utopia_database::validator::query::limit::Limit;pub struct LimitA limit query whose value is a number between 1 and max_limit.
use utopia_database::query::{Method, Query};
use utopia_database::validator::query::limit::Limit;
use utopia_database::value::Value;
let limit = Limit::new(100);
assert!(limit.check(&Query::new(Method::Limit, "", vec![Value::Int(25)])));
assert!(!limit.check(&Query::new(Method::Limit, "", vec![Value::Int(101)])));
assert_eq!(limit.description(), "Invalid limit: Value must be a valid range between 1 and 100");Default.validator::query::offset
Own page[Offset]: offset queries.
use utopia_database::validator::query::offset::Offset;pub struct OffsetAn offset query whose value is a number between 0 and max_offset.
use utopia_database::query::{Method, Query};
use utopia_database::validator::query::offset::Offset;
use utopia_database::value::Value;
let offset = Offset::new(5000);
assert!(offset.check(&Query::new(Method::Offset, "", vec![Value::Int(0)])));
assert!(!offset.check(&Query::new(Method::Offset, "", vec![Value::Int(-1)])));Default.validator::query::order
Own page[Order]: orderAsc, orderDesc and orderRandom queries.
use utopia_database::validator::query::order::Order;pub struct OrderAn order query on an attribute of the collection (any attribute when
the adapter has no schema); orderRandom needs none. A dotted
attribute orders by a relationship's attribute, which is refused.
use utopia_database::Document;
use utopia_database::query::{Method, Query};
use utopia_database::validator::query::order::Order;
use utopia_database::value::string;
let order = Order::new(&[Document::from_pairs([("key", string("name"))]).unwrap()], true);
assert!(order.check(&Query::new(Method::OrderAsc, "name", vec![])));
assert!(!order.check(&Query::new(Method::OrderAsc, "age", vec![])));
assert_eq!(order.description(), "Attribute not found in schema: age");Default.validator::query::select
Own page[Select]: select queries.
use utopia_database::validator::query::select::Select;pub struct SelectA select query of distinct attribute names, each an attribute of the
collection (any, without a schema), an internal attribute, *, or a
dotted path whose first segment is one of those.
use utopia_database::Document;
use utopia_database::query::{Method, Query};
use utopia_database::validator::query::select::Select;
use utopia_database::value::string;
let select = Select::new(&[Document::from_pairs([("key", string("name"))]).unwrap()], true);
assert!(select.check(&Query::new(Method::Select, "", vec![string("name"), string("$id")])));
assert!(!select.check(&Query::new(Method::Select, "", vec![string("name"), string("name")])));
assert_eq!(select.description(), "Duplicate attributes selected");Default.validator::roles
Own page[Roles]: lists of role strings.
use utopia_database::validator::roles::Roles;pub struct RolesA list of role strings (any, user:<id>, team:<id>/<role>, ...),
at most length of them (0: no limit), each starting with one of the
allowed names and well formed for its role.
use utopia_database::validator::roles::Roles;
use utopia_database::value::{list, string};
let roles = Roles::default();
assert!(roles.is_valid(&list([string("any"), string("user:123")])));
assert!(!roles.is_valid(&list([string("user")])));
assert_eq!(roles.description(), "Role \"user\" must have an ID value.");Default.pub const ROLES: [&str; 7] = ["any", "guests", "users", "user", "team", "member", "label"]Undocumented.
pub const USER_DIMENSIONS: [&str; 2] = ["verified", "unverified"]Roles::USER_DIMENSIONS: the dimensions of users and user roles.
validator::sequence
Own page[Sequence]: document sequence values ($sequence and id attributes).
use utopia_database::validator::sequence::Sequence;pub struct SequenceA sequence value: for the primary sequence ($sequence), a positive
integer (integer id type) or a UUIDv7 string (uuid7 id type); for
other id attributes, any string or integer. null is valid unless
primary.
use utopia_database::validator::sequence::Sequence;
use utopia_database::value::{Value, string};
let primary = Sequence::new("integer", true);
assert!(primary.is_valid(&Value::Int(1)));
assert!(!primary.is_valid(&Value::Int(0)));
assert!(Sequence::new("uuid7", true).is_valid(&string("0190d3f8-7e7c-7c8a-9a3e-123456789abc")));validator::spatial
Own page[Spatial]: values of point, linestring and polygon attributes.
use utopia_database::validator::spatial::Spatial;pub struct SpatialA geometry of one spatial type: null, a WKT string (POINT(...),
LINESTRING(...), POLYGON(...)), or coordinates as arrays: a point
[x, y], a linestring of at least two points, a polygon of closed rings
of at least four points (or one such ring). Longitudes are within
±180, latitudes within ±90.
use utopia_database::validator::spatial::Spatial;
use utopia_database::value::{list, Value};
let point = Spatial::new("point");
assert!(point.is_valid(&list([Value::Float(10.0), Value::Float(20.0)])));
assert!(!point.is_valid(&list([Value::Float(200.0), Value::Float(20.0)])));
assert_eq!(point.description(), "Value must be a valid point: Longitude (x) must be between -180 and 180, got 200");validator::structure
Own page[Structure]: documents against their collection's attributes; and
the registry of attribute formats.
use utopia_database::validator::structure::Structure;pub struct StructureA document valid for its collection: it names a collection, has every
required attribute (unless the current document holds null there),
has no unknown attribute (with a schema), and each value suits its
attribute: type, size, signedness, array-ness and format; operators
suit their attribute (OperatorValidator).
use utopia_database::Document;
use utopia_database::validator::structure::Structure;
use utopia_database::value::{Value, list, string};
let title = Document::from_pairs([
("$id", string("title")), ("type", string("string")), ("size", Value::Int(10)),
("required", Value::Bool(true)), ("array", Value::Bool(false)),
]).unwrap();
let collection = Document::from_pairs([
("$id", string("movies")), ("$collection", string("_metadata")), ("attributes", list([title.into()])),
]).unwrap();
let structure = Structure::new(collection, "integer");
let mut movie = Document::from_pairs([
("$collection", string("movies")), ("$createdAt", string("2024-01-01 00:00:00")),
("$updatedAt", string("2024-01-01 00:00:00")), ("title", string("Alien")),
]).unwrap();
assert!(structure.validate(&mut movie).unwrap());
movie.set("title", string("The Empire Strikes Back"));
assert!(!structure.validate(&mut movie).unwrap());
assert_eq!(
structure.description(),
"Invalid document structure: Attribute \"title\" has invalid type. Value must be a valid string and no longer than 10 chars"
);use utopia_database::validator::structure::StructureOptions;pub struct StructureOptionsUndocumented.
Default.validator::structure::formats
Own pageThe registry of attribute formats: named validators an attribute's
format selects, for one attribute type (an email format of
string attributes, an enum of string, a range of integer).
use utopia_database::validator::structure::formats::Format;pub struct FormatA registered format.
use utopia_database::validator::structure::formats::add;pub fn add(name: &str, factory: Factory, kind: &str)Registers (or replaces) a format.
use utopia_database::validator::structure::formats::all;pub fn all() -> Vec<Format>Every format, in registration order.
use utopia_database::validator::structure::formats::get;pub fn get(name: &str, kind: &str) -> Result<Format>Fails (crate::Kind::Database) with Format "..." not available for attribute type "..." or Unknown format validator "...".
use utopia_database::validator::structure::formats::has;pub fn has(name: &str, kind: &str) -> boolUndocumented.
use utopia_database::validator::structure::formats::remove;pub fn remove(name: &str)Undocumented.
pub type Factory = Arc<dyn Fn(&Document) -> Box<dyn utopia_validators::Validator> + Send + Sync>Builds a format's validator for an attribute (its definition: size,
formatOptions, ...).
validator::uid
Own page[Uid]: document identifiers.
use utopia_database::validator::uid::Uid;pub struct UidA document identifier: a Key without internal keys, with its own
description.
use utopia_database::validator::uid::Uid;
use utopia_database::value::string;
assert!(Uid::default().is_valid(&string("doc-1")));
assert!(!Uid::new(3).is_valid(&string("doc-1")));Default.validator::vector
Own page[Vector]: values of vector attributes.
use utopia_database::validator::vector::Vector;pub struct VectorA vector: a list (or a JSON string of a list) of exactly size
integers or floats.
use utopia_database::validator::vector::Vector;
use utopia_database::value::{list, string, Value};
let v = Vector::new(2);
assert!(v.is_valid(&list([Value::Float(1.0), Value::Int(2)])));
assert!(v.is_valid(&string("[1, 2.5]")));
assert!(!v.is_valid(&list([Value::Int(1)])));