raftdb-schema, schema and type checking
How a document schema is modelled, how a document is validated without allocation, its stored form, and what it does not do yet.
raftdb-schema depends only on raftdb-doc and has no unsafe code. A document that breaks the schema is rejected before it is stored. There is no coercion: an Int field never accepts 31.0 or "31".
Model#
Schema::new(strict): one object level.strict = truerejects fields that have no rule..field(id, Field): the rule for the field with dictionary idid, kept in aVec<Option<Slot>>indexed by id, so a lookup is an array index.Field::new(Ty), then.required(),.nullable(),.range(min, max)(inclusive).Ty:Bool,Int,F64,Ts,Str,Bytes,Arr(Box<Ty>),Obj(Box<Schema>),Any.rangemeans the value forIntandTs, the byte length forStrandBytes, the element count forArr.- Required fields are tracked in a
u64bit set per object level, so at most 64 required fields per object (BuildError::TooManyRequired).
Checking#
Schema::validate(doc) walks the fields once, checks each against its rule, then tests the required bit set. It does not allocate. The result is Ok(()) or the first Violation: Missing(id), Unknown(id), Type(id), Range(id), Malformed. An explicit null is accepted only for nullable fields or Ty::Any; a missing field is accepted unless required. Array elements must match the element type and are never null.
Stored form#
Schema::encode and decode are used by the log and checkpoints of raftdb-db. All numbers are varints, so the bytes are the same on every platform. Layout: [strict u8][rule count], then per rule in ascending field id [id][flags][type] and, when flag bit 2 is set, [min][max]. Flags: bit 0 required, bit 1 nullable, bit 2 has a range. Type tags 0 to 8 are Bool, Int, F64, Ts, Str, Bytes, Arr, Obj, Any. decode rejects truncated input, trailing bytes, unknown tags, flags above 7 and nesting deeper than 16, and never panics (tested with every truncation and every single-bit flip).
Measured#
raftdb-bench schema, 1 M corpus documents: 0 valid documents wrongly rejected, 100 % of wrong-type documents caught, and 3.16 M documents/s (about 316 ns) for 12 fields including a nested object and an array, against a target of 3 M/s. The margin is 5 %.
Not supported yet#
Unique and foreign-key relations, defaults, enums, string patterns and cross-field checks are not in this crate. Changing the schema of a collection that has data (migration, backfill) is not designed.