rydantic 0.8.0-beta.1

Type-driven validation, JSON Schema, Cap'n Proto, Axum and SQLx models for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Unified JSON models for Rust.
//!
//! ```
//! use rydantic::{Model, SchemaMode};
//!
//! #[derive(Debug, Model)]
//! struct User {
//!     #[model(trim, min_length = 3)]
//!     name: String,
//!     #[model(ge = 18, le = 120)]
//!     age: u8,
//! }
//!
//! let user = User::parse_json(r#"{"name":" Alice ","age":25}"#)?;
//! assert_eq!(user.name, "Alice");
//! assert!(User::json_schema(SchemaMode::Output).is_object());
//! # Ok::<(), rydantic::ValidationErrors>(())
//! ```

extern crate self as rydantic;

mod asynchronous;
#[cfg(feature = "axum")]
pub mod axum;
#[cfg(feature = "partial-json")]
pub mod partial_json;
#[cfg(feature = "sqlx")]
pub mod sql;
#[cfg(all(feature = "sqlx", feature = "derive"))]
pub use rydantic_derive::SqlModel;
#[cfg(feature = "sqlx")]
pub use sql::{SqlError, SqlModel};
#[cfg(feature = "sqlx")]
pub use sqlx;
mod borrowed;
#[cfg(feature = "capnp")]
pub mod capnp_support;
#[cfg(feature = "chrono")]
mod dates;
#[cfg(feature = "decimal")]
mod decimal;
mod direct;
#[cfg(any(feature = "phone", feature = "country", feature = "currency"))]
pub mod domain;
#[cfg(feature = "capnp")]
pub use capnp;
#[cfg(feature = "capnp")]
pub use capnp_support::CapnpSchema;
#[cfg(feature = "capnp")]
pub use capnp_support::{CapnpEnum, CapnpModel};
/// Derive a complete Cap'n Proto protocol and bindings from an inline model module.
/// Every model must explicitly derive `Model` (an imported alias also works).
#[doc(inline)]
#[cfg(all(feature = "capnp", feature = "derive"))]
pub use rydantic_derive::__rydantic_capnp_models_runtime as capnp_models;
#[doc(hidden)]
#[cfg(all(feature = "capnp", feature = "derive"))]
pub use rydantic_derive::{__RydanticCapnpConfigured, __rydantic_capnp_discard};
#[cfg(feature = "dynamic")]
mod dynamic;
mod error;
mod object;
pub mod pipeline;
pub mod rules;
pub mod schema;
#[cfg(feature = "settings")]
pub mod settings;
pub mod stream;
mod types;

pub use asynchronous::{AsyncCheck, AsyncValidated, BoxFuture};
pub use borrowed::{BorrowModel, BorrowType, BorrowValidated, Input};
#[cfg(feature = "chrono")]
pub use chrono;
#[cfg(feature = "dynamic")]
pub use dynamic::{DynamicModel, SchemaError};
pub use error::{Context, PathSegment, Stage, ValidationError, ValidationErrors};
pub use object::{ExtraFields, ObjectType};
#[cfg(feature = "decimal")]
pub use rust_decimal;
#[cfg(feature = "derive")]
pub use rydantic_derive::Model;
pub use schema::{LocalRule, SchemaContext, SchemaMode, SchemaReport};
pub use serde_json::value::RawValue;
pub use serde_json::{json, Value};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeKind {
    String,
    Number,
    Boolean,
    Array,
    Object,
    Any,
    Decimal,
}

/// Extension point for JSON-compatible Rust types.
///
/// A decoder must record an error whenever it returns None. It may return a
/// constructed value together with constraint errors; public entry points reject it.
pub trait JsonType: Sized {
    fn decode(value: Value, ctx: &mut Context, coerce: bool) -> Option<Self>;
    /// Decode a raw subtree. Custom types can override this to bypass Value entirely.
    fn decode_input(input: Input<'_>, ctx: &mut Context, coerce: bool) -> Option<Self> {
        Self::decode(input.into_value(ctx)?, ctx, coerce)
    }
    fn prepare_default(self, ctx: &mut Context) -> Option<Self> {
        let value = self.encode_input(ctx);
        Self::decode(value, ctx, false)
    }
    fn encode(&self, ctx: &mut Context) -> Value;
    /// Representation using input aliases and including output-excluded fields.
    /// Used to validate typed defaults without losing required input information.
    fn encode_input(&self, ctx: &mut Context) -> Value {
        self.encode(ctx)
    }
    fn schema(ctx: &mut SchemaContext, coerce: bool) -> Value;
    fn validate_into(&self, _ctx: &mut Context) {}
    fn normalize(self, rules: &rules::Rules, ctx: &mut Context) -> Option<Self> {
        if !rules.normalizes() {
            return Some(self);
        }
        let mut value = self.encode_input(ctx);
        rules.prepare(&mut value);
        Self::decode(value, ctx, false)
    }
    fn validate_rules(&self, rules: &rules::Rules, ctx: &mut Context) {
        rules.validate(&self.encode(ctx), ctx);
    }
    fn async_required(_seen: &mut std::collections::HashSet<&'static str>) -> bool {
        false
    }
    fn missing() -> Option<Self> {
        None
    }
    fn allows_missing() -> bool {
        false
    }
    fn kind() -> TypeKind {
        TypeKind::Any
    }
}

/// Marker traits make invalid attribute/type combinations fail during compilation.
pub trait StringType {}
pub trait NumericType {}
pub trait LengthType {}

/// High-level model API generated by `#[derive(Model)]`.
pub trait Model: JsonType {
    /// Parse with explicit, request-owned business context. Context types must be
    /// owned (`'static`), Send and Sync; callbacks retrieve them with
    /// `Context::require_data`. No context is stored in the resulting model.
    fn parse_json_with_context<C: std::any::Any + Send + Sync>(
        input: &str,
        context: std::sync::Arc<C>,
    ) -> Result<Self, ValidationErrors> {
        let raw = serde_json::from_str::<&RawValue>(input).map_err(borrowed::json_error)?;
        Self::parse_raw_with_context(raw, context)
    }
    fn parse_slice_with_context<C: std::any::Any + Send + Sync>(
        input: &[u8],
        context: std::sync::Arc<C>,
    ) -> Result<Self, ValidationErrors> {
        let raw = serde_json::from_slice::<&RawValue>(input).map_err(borrowed::json_error)?;
        Self::parse_raw_with_context(raw, context)
    }
    fn parse_reader_with_context<R: std::io::Read, C: std::any::Any + Send + Sync>(
        reader: R,
        context: std::sync::Arc<C>,
    ) -> Result<Self, ValidationErrors> {
        let raw =
            serde_json::from_reader::<_, Box<RawValue>>(reader).map_err(borrowed::json_error)?;
        Self::parse_raw_with_context(&raw, context)
    }
    fn parse_raw_with_context<C: std::any::Any + Send + Sync>(
        raw: &RawValue,
        context: std::sync::Arc<C>,
    ) -> Result<Self, ValidationErrors> {
        asynchronous::sync_guard(Self::async_required(&mut std::collections::HashSet::new()))?;
        let mut ctx = Context::with_data(context);
        let model = Self::decode_input(Input::Borrowed(raw), &mut ctx, false);
        ctx.finish(model)
    }
    fn parse_value_with_context<C: std::any::Any + Send + Sync>(
        value: Value,
        context: std::sync::Arc<C>,
    ) -> Result<Self, ValidationErrors> {
        asynchronous::sync_guard(Self::async_required(&mut std::collections::HashSet::new()))?;
        let mut ctx = Context::with_data(context);
        let model = Self::decode(value, &mut ctx, false);
        ctx.finish(model)
    }
    fn validate_with_context<C: std::any::Any + Send + Sync>(
        &self,
        context: std::sync::Arc<C>,
    ) -> Result<(), ValidationErrors> {
        asynchronous::sync_guard(Self::async_required(&mut std::collections::HashSet::new()))?;
        let mut ctx = Context::with_data(context);
        self.validate_into(&mut ctx);
        ctx.result()
    }
    fn dump_with_context<C: std::any::Any + Send + Sync>(
        &self,
        context: std::sync::Arc<C>,
    ) -> Result<Value, ValidationErrors> {
        self.validate_with_context(context.clone())?;
        let mut ctx = Context::with_data(context);
        let value = self.encode(&mut ctx);
        ctx.finish(Some(value))
    }
    fn dump_json_with_context<C: std::any::Any + Send + Sync>(
        &self,
        context: std::sync::Arc<C>,
    ) -> Result<String, ValidationErrors> {
        serde_json::to_string(&self.dump_with_context(context)?).map_err(|error| {
            ValidationError::new("serialization", error.to_string())
                .with_stage(Stage::Serialize)
                .into()
        })
    }
    fn parse_json_async_with_context<C: std::any::Any + Send + Sync>(
        input: &str,
        context: std::sync::Arc<C>,
    ) -> impl std::future::Future<Output = Result<Self, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            let raw = serde_json::from_str::<&RawValue>(input).map_err(borrowed::json_error)?;
            Self::parse_raw_async_with_context(raw, context).await
        }
    }
    fn parse_raw_async_with_context<C: std::any::Any + Send + Sync>(
        raw: &RawValue,
        context: std::sync::Arc<C>,
    ) -> impl std::future::Future<Output = Result<Self, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            let mut ctx = Context::with_data(context.clone());
            let model = Self::decode_input(Input::Borrowed(raw), &mut ctx, false);
            let model = ctx.finish(model)?;
            let mut ctx = Context::with_data(context);
            model.check_async(&mut ctx).await;
            ctx.result()?;
            Ok(model)
        }
    }
    fn parse_value_async_with_context<C: std::any::Any + Send + Sync>(
        value: Value,
        context: std::sync::Arc<C>,
    ) -> impl std::future::Future<Output = Result<Self, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            let mut ctx = Context::with_data(context.clone());
            let model = Self::decode(value, &mut ctx, false);
            let model = ctx.finish(model)?;
            let mut ctx = Context::with_data(context);
            model.check_async(&mut ctx).await;
            ctx.result()?;
            Ok(model)
        }
    }
    fn validate_async_with_context<C: std::any::Any + Send + Sync>(
        &self,
        context: std::sync::Arc<C>,
    ) -> impl std::future::Future<Output = Result<(), ValidationErrors>> + Send
    where
        Self: AsyncCheck,
    {
        async move {
            let mut ctx = Context::with_data(context.clone());
            self.validate_into(&mut ctx);
            ctx.result()?;
            let mut ctx = Context::with_data(context);
            self.check_async(&mut ctx).await;
            ctx.result()
        }
    }
    fn dump_async_with_context<C: std::any::Any + Send + Sync>(
        &self,
        context: std::sync::Arc<C>,
    ) -> impl std::future::Future<Output = Result<Value, ValidationErrors>> + Send
    where
        Self: AsyncCheck,
    {
        async move {
            self.validate_async_with_context(context.clone()).await?;
            let mut ctx = Context::with_data(context);
            let value = self.encode(&mut ctx);
            ctx.finish(Some(value))
        }
    }
    fn dump_json_async_with_context<C: std::any::Any + Send + Sync>(
        &self,
        context: std::sync::Arc<C>,
    ) -> impl std::future::Future<Output = Result<String, ValidationErrors>> + Send
    where
        Self: AsyncCheck,
    {
        async move { Ok(self.dump_async_with_context(context).await?.to_string()) }
    }

    /// Strict by default. Explicit field-level `coerce` is applied by the derive.
    fn parse_json(input: &str) -> Result<Self, ValidationErrors> {
        let raw = serde_json::from_str::<&RawValue>(input).map_err(borrowed::json_error)?;
        Self::parse_raw(raw)
    }
    fn parse_slice(input: &[u8]) -> Result<Self, ValidationErrors> {
        let raw = serde_json::from_slice::<&RawValue>(input).map_err(borrowed::json_error)?;
        Self::parse_raw(raw)
    }
    fn parse_raw(raw: &RawValue) -> Result<Self, ValidationErrors> {
        asynchronous::sync_guard(Self::async_required(&mut std::collections::HashSet::new()))?;
        let mut ctx = Context::new();
        let model = Self::decode_input(Input::Borrowed(raw), &mut ctx, false);
        ctx.finish(model)
    }
    fn parse_value(value: Value) -> Result<Self, ValidationErrors> {
        asynchronous::sync_guard(Self::async_required(&mut std::collections::HashSet::new()))?;
        let mut ctx = Context::new();
        let model = Self::decode(value, &mut ctx, false);
        ctx.finish(model)
    }
    /// Recheck a value constructed or mutated in Rust. Does not normalize it.
    fn validate(&self) -> Result<(), ValidationErrors> {
        asynchronous::sync_guard(Self::async_required(&mut std::collections::HashSet::new()))?;
        let mut ctx = Context::new();
        self.validate_into(&mut ctx);
        ctx.result()
    }
    /// Revalidate before serialization, including fields excluded from the output.
    fn dump(&self) -> Result<Value, ValidationErrors> {
        self.validate()?;
        let mut ctx = Context::new();
        let value = self.encode(&mut ctx);
        ctx.finish(Some(value))
    }
    fn dump_json(&self) -> Result<String, ValidationErrors> {
        let value = self.dump()?;
        serde_json::to_string(&value).map_err(|error| {
            ValidationError::new("serialization", error.to_string())
                .with_stage(Stage::Serialize)
                .into()
        })
    }
    fn json_schema(mode: SchemaMode) -> Value {
        let mut ctx = SchemaContext::new(mode);
        let root = Self::schema(&mut ctx, false);
        ctx.finish(root)
    }
    fn schema_report(mode: SchemaMode) -> SchemaReport {
        SchemaReport::new(Self::json_schema(mode))
    }
    fn parse_reader<R: std::io::Read>(reader: R) -> Result<Self, ValidationErrors> {
        let raw =
            serde_json::from_reader::<_, Box<RawValue>>(reader).map_err(borrowed::json_error)?;
        Self::parse_raw(&raw)
    }
    fn parse_json_async(
        input: &str,
    ) -> impl std::future::Future<Output = Result<Self, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            let raw = serde_json::from_str::<&RawValue>(input).map_err(borrowed::json_error)?;
            Self::parse_raw_async(raw).await
        }
    }
    fn parse_raw_async(
        raw: &RawValue,
    ) -> impl std::future::Future<Output = Result<Self, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            let mut ctx = Context::new();
            let model = Self::decode_input(Input::Borrowed(raw), &mut ctx, false);
            let model = ctx.finish(model)?;
            let mut ctx = Context::new();
            model.check_async(&mut ctx).await;
            ctx.result()?;
            Ok(model)
        }
    }
    fn parse_value_async(
        value: Value,
    ) -> impl std::future::Future<Output = Result<Self, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            let mut ctx = Context::new();
            let model = Self::decode(value, &mut ctx, false);
            let model = ctx.finish(model)?;
            let mut ctx = Context::new();
            model.check_async(&mut ctx).await;
            ctx.result()?;
            Ok(model)
        }
    }
    fn validate_async(
        &self,
    ) -> impl std::future::Future<Output = Result<(), ValidationErrors>> + Send
    where
        Self: AsyncCheck,
    {
        async move {
            let mut ctx = Context::new();
            self.validate_into(&mut ctx);
            ctx.result()?;
            let mut ctx = Context::new();
            self.check_async(&mut ctx).await;
            ctx.result()
        }
    }
    fn dump_async(
        &self,
    ) -> impl std::future::Future<Output = Result<Value, ValidationErrors>> + Send
    where
        Self: AsyncCheck,
    {
        async move {
            self.validate_async().await?;
            let mut ctx = Context::new();
            let value = self.encode(&mut ctx);
            ctx.finish(Some(value))
        }
    }
    fn dump_json_async(
        &self,
    ) -> impl std::future::Future<Output = Result<String, ValidationErrors>> + Send
    where
        Self: AsyncCheck,
    {
        async move { Ok(self.dump_async().await?.to_string()) }
    }
    fn parse_validated_json_async(
        input: &str,
    ) -> impl std::future::Future<Output = Result<AsyncValidated<Self>, ValidationErrors>> + Send
    where
        Self: AsyncCheck + Send,
    {
        async move {
            Self::parse_json_async(input)
                .await
                .map(AsyncValidated::checked)
        }
    }
    fn parse_validated_json(input: &str) -> Result<Validated<Self>, ValidationErrors> {
        Self::parse_json(input).map(Validated)
    }
}

/// Read-only access to a successfully checked model. No DerefMut or unchecked constructor.
/// Interior-mutability types can weaken this guarantee; their JsonType implementation
/// must document that behavior.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Validated<T: Model>(T);
impl<T: Model> Validated<T> {
    pub fn new(value: T) -> Result<Self, ValidationErrors> {
        value.validate()?;
        Ok(Self(value))
    }
    pub fn get(&self) -> &T {
        &self.0
    }
    pub fn into_inner(self) -> T {
        self.0
    }
}
impl<T: Model> std::ops::Deref for Validated<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}
impl<T: Model> serde::Serialize for Validated<T> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let value = self.0.dump().map_err(serde::ser::Error::custom)?;
        serde::Serialize::serialize(&value, serializer)
    }
}
impl<'de, T: Model> serde::Deserialize<'de> for Validated<T> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = <Box<RawValue> as serde::Deserialize>::deserialize(deserializer)?;
        T::parse_raw(&raw)
            .map(Self)
            .map_err(serde::de::Error::custom)
    }
}

#[doc(hidden)]
pub mod __private {
    pub use crate::object::{check_names, flatten_schema, merge};
    pub use regex;
    pub use serde;
    pub use serde_json;
    pub fn number(literal: &str) -> serde_json::Number {
        literal
            .parse()
            .expect("numeric literal checked by the derive macro")
    }
}