reactive_graph_graph/instances/relations/
relation_instance.rs

1use std::cmp::Ordering;
2use std::fmt::Display;
3use std::fmt::Formatter;
4use std::hash::Hash;
5use std::hash::Hasher;
6use std::ops::Deref;
7use std::ops::DerefMut;
8
9use const_format::formatcp;
10use dashmap::DashMap;
11use dashmap::iter::OwningIter;
12use schemars::JsonSchema;
13use schemars::Schema;
14use schemars::SchemaGenerator;
15use schemars::json_schema;
16use serde::Deserialize;
17use serde::Deserializer;
18use serde::Serialize;
19use serde::Serializer;
20use serde_json::Map;
21use serde_json::Value;
22use std::borrow::Cow;
23use typed_builder::TypedBuilder;
24use uuid::Uuid;
25
26use crate::AddExtensionError;
27use crate::ComponentTypeId;
28use crate::ComponentTypeIdContainer;
29use crate::ComponentTypeIds;
30use crate::Extension;
31use crate::ExtensionContainer;
32use crate::ExtensionTypeId;
33use crate::Extensions;
34use crate::InstanceId;
35use crate::JSON_SCHEMA_ID_URI_PREFIX;
36use crate::MutablePropertyInstanceSetter;
37use crate::NamedInstanceContainer;
38use crate::NamespaceSegment;
39use crate::NamespacedType;
40use crate::NamespacedTypeGetter;
41use crate::PropertyInstanceGetter;
42use crate::PropertyInstances;
43use crate::RelationInstanceId;
44use crate::RelationInstanceTypeId;
45use crate::RelationTypeId;
46use crate::RelationTypeIds;
47use crate::RemoveExtensionError;
48use crate::TypeDefinition;
49use crate::TypeDefinitionGetter;
50use crate::TypeIdType;
51use crate::UpdateExtensionError;
52use crate::namespace::Namespace;
53
54#[cfg(any(test, feature = "test"))]
55use crate::NamespacedTypeError;
56#[cfg(any(test, feature = "test"))]
57use crate::RandomInstance;
58#[cfg(any(test, feature = "test"))]
59use crate::RandomInstances;
60#[cfg(any(test, feature = "test"))]
61use crate::RandomNamespacedTypeId;
62#[cfg(any(test, feature = "test"))]
63use crate::RandomNamespacedTypes;
64#[cfg(any(test, feature = "test"))]
65use default_test::DefaultTest;
66#[cfg(any(test, feature = "test"))]
67use rand::Rng;
68#[cfg(any(test, feature = "test"))]
69use reactive_graph_utils_test::r_string;
70
71pub const JSON_SCHEMA_ID_RELATION_INSTANCE: &str = formatcp!("{}/relation-instance.schema.json", JSON_SCHEMA_ID_URI_PREFIX);
72
73/// Relation instances are edges from an outbound entity instance to an
74/// inbound entity instance.
75///
76/// The relation instance is of a relation type. The relation type defines
77/// the entity types of the outbound entity instance and the inbound entity
78/// instance. Furthermore, the relation type defines which properties
79/// (name, data type, socket type) a relation instance have to have.
80///
81/// In contrast to the relation type, the relation instance stores values/
82/// documents in its properties.
83#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TypedBuilder)]
84#[serde(tag = "$id", rename = "https://schema.reactive-graph.io/schema/json/relation-instance.schema.json")]
85#[schemars(
86    title = "RelationInstance",
87    rename = "RelationInstance",
88    deny_unknown_fields,
89    extend("$id" = JSON_SCHEMA_ID_RELATION_INSTANCE),
90    transform = add_json_schema_id_property
91)]
92pub struct RelationInstance {
93    /// The id of the outbound entity instance.
94    pub outbound_id: Uuid,
95
96    /// The relation instance id is unique and consists of the relation type and an instance_id.
97    #[serde(flatten)]
98    #[builder(setter(into))]
99    pub ty: RelationInstanceTypeId,
100
101    /// The id of the inbound entity instance.
102    pub inbound_id: Uuid,
103
104    /// The name of the relation instance.
105    #[serde(default = "String::new")]
106    #[builder(default, setter(into))]
107    pub name: String,
108
109    /// Textual description of the relation instance.
110    #[serde(default = "String::new")]
111    #[builder(default, setter(into))]
112    pub description: String,
113
114    /// The properties of then relation instance.
115    ///
116    /// Each property is represented by its name (String) and it's value. The value is
117    /// a representation of a JSON. Therefore, the value can be boolean, number, string,
118    /// array or an object. For more information about the data types please look at
119    /// <https://docs.serde.rs/serde_json/value/enum.Value.html>
120    #[serde(default = "PropertyInstances::new")]
121    #[builder(default, setter(into))]
122    pub properties: PropertyInstances,
123
124    /// The components of the entity instance.
125    #[serde(default = "ComponentTypeIds::new")]
126    #[builder(default, setter(into))]
127    pub components: ComponentTypeIds,
128
129    /// Relation instance specific extensions.
130    #[serde(default = "Extensions::new")]
131    #[builder(default, setter(into))]
132    pub extensions: Extensions,
133}
134
135impl RelationInstance {
136    /// Constructs a new relation instance with the given outbound_id, type, inbound_id and properties
137    pub fn new<T: Into<RelationInstanceTypeId>, P: Into<PropertyInstances>>(outbound_id: Uuid, ty: T, inbound_id: Uuid, properties: P) -> RelationInstance {
138        RelationInstance {
139            outbound_id,
140            ty: ty.into(),
141            inbound_id,
142            name: String::new(),
143            description: String::new(),
144            properties: properties.into(),
145            components: ComponentTypeIds::new(),
146            extensions: Extensions::new(),
147        }
148    }
149
150    /// Constructs a new relation instance with the given outbound_id, type, inbound_id but without properties
151    pub fn new_without_properties<T: Into<RelationInstanceTypeId>>(outbound_id: Uuid, ty: T, inbound_id: Uuid) -> RelationInstance {
152        RelationInstance {
153            outbound_id,
154            ty: ty.into(),
155            inbound_id,
156            name: String::new(),
157            description: String::new(),
158            properties: PropertyInstances::new(),
159            components: ComponentTypeIds::new(),
160            extensions: Extensions::new(),
161        }
162    }
163
164    /// Returns the relation instance id.
165    pub fn id(&self) -> RelationInstanceId {
166        RelationInstanceId::builder()
167            .outbound_id(self.outbound_id)
168            .ty(self.ty.clone())
169            .inbound_id(self.inbound_id)
170            .build()
171    }
172
173    /// Returns the inner relation type id.
174    pub fn relation_type_id(&self) -> RelationTypeId {
175        self.ty.relation_type_id()
176    }
177
178    /// Returns the relation instance type id.
179    pub fn instance_id(&self) -> InstanceId {
180        self.ty.instance_id()
181    }
182}
183
184impl NamedInstanceContainer for RelationInstance {
185    fn name(&self) -> String {
186        self.name.clone()
187    }
188
189    fn description(&self) -> String {
190        self.description.clone()
191    }
192}
193
194impl PropertyInstanceGetter for RelationInstance {
195    fn get(&self, property_name: &str) -> Option<Value> {
196        self.properties.get(property_name.into())
197    }
198
199    fn as_bool(&self, property_name: &str) -> Option<bool> {
200        self.properties.as_bool(property_name.into())
201    }
202
203    fn as_u64(&self, property_name: &str) -> Option<u64> {
204        self.properties.as_u64(property_name.into())
205    }
206
207    fn as_i64(&self, property_name: &str) -> Option<i64> {
208        self.properties.as_i64(property_name.into())
209    }
210
211    fn as_f64(&self, property_name: &str) -> Option<f64> {
212        self.properties.as_f64(property_name.into())
213    }
214
215    fn as_string(&self, property_name: &str) -> Option<String> {
216        self.properties.as_string(property_name.into())
217    }
218
219    fn as_array(&self, property_name: &str) -> Option<Vec<Value>> {
220        self.properties.as_array(property_name.into())
221    }
222
223    fn as_object(&self, property_name: &str) -> Option<Map<String, Value>> {
224        self.properties.as_object(property_name.into())
225    }
226}
227
228impl MutablePropertyInstanceSetter for RelationInstance {
229    fn set<S: Into<String>>(&mut self, property_name: S, value: Value) {
230        self.properties.set(property_name.into(), value);
231    }
232}
233
234impl ComponentTypeIdContainer for RelationInstance {
235    fn is_a(&self, ty: &ComponentTypeId) -> bool {
236        self.components.is_a(ty)
237    }
238
239    fn add_component<C: Into<ComponentTypeId>>(&self, ty: C) -> bool {
240        self.components.add_component(ty)
241    }
242
243    fn add_components<C: Into<ComponentTypeIds>>(&mut self, components_to_add: C) {
244        self.components.add_components(components_to_add)
245    }
246
247    fn remove_component(&self, ty: &ComponentTypeId) -> Option<ComponentTypeId> {
248        self.components.remove_component(ty)
249    }
250
251    fn remove_components<C: Into<ComponentTypeIds>>(&mut self, components_to_remove: C) {
252        self.components.remove_components(components_to_remove)
253    }
254
255    fn get_components_cloned(&self) -> ComponentTypeIds {
256        self.components.clone()
257    }
258}
259
260impl ExtensionContainer for RelationInstance {
261    fn has_own_extension(&self, ty: &ExtensionTypeId) -> bool {
262        self.extensions.has_own_extension(ty)
263    }
264
265    fn get_own_extension(&self, ty: &ExtensionTypeId) -> Option<Extension> {
266        self.extensions.get_own_extension(ty)
267    }
268
269    fn add_extension<E: Into<Extension>>(&self, extension: E) -> Result<ExtensionTypeId, AddExtensionError> {
270        self.extensions.add_extension(extension)
271    }
272
273    fn update_extension<T: Into<ExtensionTypeId>, E: Into<Extension>>(&self, ty: T, extension: E) -> Result<Extension, UpdateExtensionError> {
274        self.extensions.update_extension(ty, extension)
275    }
276
277    fn remove_extension<T: Into<ExtensionTypeId>>(&self, ty: T) -> Result<Extension, RemoveExtensionError> {
278        self.extensions.remove_extension(ty)
279    }
280
281    fn merge_extensions<E: Into<Extensions>>(&mut self, extensions_to_merge: E) {
282        self.extensions.merge_extensions(extensions_to_merge)
283    }
284
285    fn get_own_extensions_cloned(&self) -> Extensions {
286        self.extensions.clone()
287    }
288}
289
290impl NamespacedTypeGetter for RelationInstance {
291    fn namespaced_type(&self) -> NamespacedType {
292        self.ty.namespaced_type()
293    }
294
295    fn namespace(&self) -> Namespace {
296        self.ty.namespace()
297    }
298
299    fn path(&self) -> Namespace {
300        self.ty.path()
301    }
302
303    fn type_name(&self) -> NamespaceSegment {
304        self.ty.type_name()
305    }
306}
307
308impl TypeDefinitionGetter for RelationInstance {
309    fn type_definition(&self) -> TypeDefinition {
310        self.ty.type_definition()
311    }
312
313    fn type_id_type() -> TypeIdType {
314        TypeIdType::RelationType
315    }
316}
317
318impl PartialEq<RelationInstanceId> for RelationInstance {
319    fn eq(&self, id: &RelationInstanceId) -> bool {
320        self.id() == *id
321    }
322}
323
324impl PartialOrd<Self> for RelationInstance {
325    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
326        Some(self.cmp(other))
327    }
328}
329
330impl Ord for RelationInstance {
331    fn cmp(&self, other: &Self) -> Ordering {
332        let id = self.id();
333        let other_id = other.id();
334        id.cmp(&other_id)
335    }
336}
337
338impl Display for RelationInstance {
339    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
340        write!(f, "{}", self.id())
341        // write!(f, "{}--[{}]-->{}", self.outbound_id, &self.ty, self.inbound_id)
342    }
343}
344
345#[derive(Clone, Debug, Default)]
346// #[derive(Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema)]
347pub struct RelationInstances(DashMap<RelationInstanceId, RelationInstance>);
348
349impl RelationInstances {
350    pub fn new() -> Self {
351        RelationInstances(DashMap::new())
352    }
353
354    pub fn push<E: Into<RelationInstance>>(&self, relation_instance: E) {
355        let relation_instance = relation_instance.into();
356        self.0.insert(relation_instance.id(), relation_instance);
357    }
358
359    pub fn to_vec(&self) -> Vec<RelationInstance> {
360        let mut items: Vec<_> = self.iter().map(|item| item.value().clone()).collect();
361        items.sort();
362        items
363    }
364
365    // TODO: deduplicate?
366    pub fn get_type_ids(&self) -> RelationTypeIds {
367        self.iter().map(|r| r.relation_type_id()).collect()
368    }
369}
370
371impl Deref for RelationInstances {
372    type Target = DashMap<RelationInstanceId, RelationInstance>;
373
374    fn deref(&self) -> &Self::Target {
375        &self.0
376    }
377}
378
379impl DerefMut for RelationInstances {
380    fn deref_mut(&mut self) -> &mut Self::Target {
381        &mut self.0
382    }
383}
384
385impl IntoIterator for RelationInstances {
386    type Item = (RelationInstanceId, RelationInstance);
387    type IntoIter = OwningIter<RelationInstanceId, RelationInstance>;
388
389    fn into_iter(self) -> Self::IntoIter {
390        self.0.into_iter()
391    }
392}
393
394impl PartialEq for RelationInstances {
395    fn eq(&self, other: &Self) -> bool {
396        self.0.iter().all(|self_entity_instance| other.contains_key(&self_entity_instance.id()))
397            && other.iter().all(|other_entity_instance| self.contains_key(&other_entity_instance.id()))
398    }
399}
400
401impl Eq for RelationInstances {}
402
403impl Hash for RelationInstances {
404    fn hash<H: Hasher>(&self, state: &mut H) {
405        self.to_vec().hash(state);
406    }
407}
408
409impl Serialize for RelationInstances {
410    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
411    where
412        S: Serializer,
413    {
414        serializer.collect_seq(self.iter())
415    }
416}
417
418impl<'de> Deserialize<'de> for RelationInstances {
419    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
420    where
421        D: Deserializer<'de>,
422    {
423        Ok(Vec::<RelationInstance>::deserialize(deserializer)?.into())
424    }
425}
426
427impl JsonSchema for RelationInstances {
428    fn schema_name() -> Cow<'static, str> {
429        "RelationInstances".into()
430    }
431
432    fn json_schema(schema_generator: &mut SchemaGenerator) -> Schema {
433        let sub_schema: Schema = schema_generator.subschema_for::<RelationInstance>();
434        json_schema!({
435            "type": "array",
436            "items": sub_schema,
437            "description": "Relation Instances",
438        })
439    }
440}
441
442impl From<Vec<RelationInstance>> for RelationInstances {
443    fn from(relation_instances: Vec<RelationInstance>) -> Self {
444        Self(
445            relation_instances
446                .into_iter()
447                .map(|relation_instance| (relation_instance.id(), relation_instance))
448                .collect(),
449        )
450    }
451}
452
453impl From<RelationInstances> for Vec<RelationInstance> {
454    fn from(relation_instances: RelationInstances) -> Self {
455        relation_instances.to_vec()
456    }
457}
458
459impl From<&RelationInstances> for Vec<RelationInstance> {
460    fn from(relation_instances: &RelationInstances) -> Self {
461        relation_instances.0.iter().map(|relation_instance| relation_instance.clone()).collect()
462    }
463}
464
465impl From<DashMap<RelationInstanceId, RelationInstance>> for RelationInstances {
466    fn from(relation_instances: DashMap<RelationInstanceId, RelationInstance>) -> Self {
467        Self(relation_instances)
468    }
469}
470
471impl From<&DashMap<RelationInstanceId, RelationInstance>> for RelationInstances {
472    fn from(relation_instances: &DashMap<RelationInstanceId, RelationInstance>) -> Self {
473        Self(relation_instances.clone())
474    }
475}
476
477impl From<RelationInstances> for DashMap<RelationInstanceId, RelationInstance> {
478    fn from(relation_instances: RelationInstances) -> Self {
479        relation_instances.0
480    }
481}
482
483impl FromIterator<RelationInstance> for RelationInstances {
484    fn from_iter<I: IntoIterator<Item = RelationInstance>>(iter: I) -> Self {
485        let relation_instances = Self::new();
486        for relation_instance in iter {
487            relation_instances.insert(relation_instance.id(), relation_instance);
488        }
489        relation_instances
490    }
491}
492
493#[cfg(any(test, feature = "test"))]
494impl RandomInstance for RelationInstance {
495    type Error = NamespacedTypeError;
496    type TypeId = RelationInstanceTypeId;
497
498    fn random_instance() -> Result<Self, NamespacedTypeError> {
499        Self::random_instance_with_id(&RelationInstanceTypeId::random_type_id()?)
500    }
501
502    fn random_instance_with_id(ty: &Self::TypeId) -> Result<Self, Self::Error> {
503        Ok(RelationInstance::builder()
504            .outbound_id(Uuid::new_v4())
505            .ty(ty)
506            .inbound_id(Uuid::new_v4())
507            .name(r_string())
508            .description(r_string())
509            .properties(PropertyInstances::default_test())
510            .extensions(Extensions::random_types(0..10)?)
511            .build())
512    }
513}
514
515#[cfg(any(test, feature = "test"))]
516impl RandomInstances for RelationInstances {
517    type Error = NamespacedTypeError;
518
519    fn random_instances() -> Result<Self, NamespacedTypeError> {
520        let instances = Self::new();
521        let mut rng = rand::rng();
522        for _ in 0..rng.random_range(0..10) {
523            instances.push(RelationInstance::random_instance()?);
524        }
525        Ok(instances)
526    }
527}
528
529fn add_json_schema_id_property(schema: &mut Schema) {
530    crate::json_schema::add_json_schema_id_property(schema, JSON_SCHEMA_ID_RELATION_INSTANCE);
531}
532
533#[cfg(test)]
534mod tests {
535    use schemars::schema_for;
536    use serde_json::json;
537    use std::ops::Index;
538    use std::str::FromStr;
539    use uuid::Uuid;
540
541    use crate::ComponentTypeId;
542    use crate::ComponentTypeIdContainer;
543    use crate::ComponentTypeIds;
544    use crate::Extension;
545    use crate::ExtensionContainer;
546    use crate::ExtensionTypeId;
547    use crate::Extensions;
548    use crate::InstanceId;
549    use crate::MutablePropertyInstanceSetter;
550    use crate::PropertyInstanceGetter;
551    use crate::PropertyInstances;
552    use crate::RandomInstance;
553    use crate::RandomNamespacedType;
554    use crate::RandomNamespacedTypeId;
555    use crate::RelationInstance;
556    use crate::RelationInstanceId;
557    use crate::RelationInstanceTypeId;
558    use crate::RelationTypeId;
559    use reactive_graph_utils_test::r_string;
560
561    #[test]
562    pub fn build_relation_instance() {
563        let relation_ty = RelationTypeId::random_type_id().unwrap();
564        let instance_id = InstanceId::Id(Uuid::from_str("7839aec8-07ea-41d1-84e5-f00b59d62c3e").unwrap());
565        let relation_instance_ty = RelationInstanceTypeId::new(relation_ty.clone(), instance_id.clone());
566        let outbound_id = Uuid::new_v4();
567        let inbound_id = Uuid::new_v4();
568        let name = r_string();
569        let description = r_string();
570        let property_name = r_string();
571        let property_value = json!(r_string());
572        let component_ty = ComponentTypeId::random_type_id().unwrap();
573        let components = ComponentTypeIds::new().component(&component_ty);
574        let properties = PropertyInstances::new().property(property_name.clone(), property_value.clone());
575        let extension = Extension::random_type().unwrap();
576        let extensions = Extensions::new().extension(extension.clone());
577        let relation_instance = RelationInstance::builder()
578            .outbound_id(outbound_id)
579            .ty(&relation_instance_ty)
580            .inbound_id(inbound_id)
581            .name(&name)
582            .description(&description)
583            .components(components.clone())
584            .properties(properties.clone())
585            .extensions(extensions.clone())
586            .build();
587        assert_eq!(outbound_id, relation_instance.outbound_id);
588        assert_eq!(relation_instance_ty, relation_instance.ty);
589        assert_eq!(relation_ty, relation_instance.relation_type_id());
590        assert_eq!(instance_id, relation_instance.instance_id());
591        assert_eq!(inbound_id, relation_instance.inbound_id);
592        assert_eq!(name, relation_instance.name);
593        assert_eq!(description, relation_instance.description);
594        assert_eq!(components, relation_instance.components);
595        assert!(relation_instance.is_a(&component_ty));
596        assert_eq!(properties, relation_instance.properties);
597        assert_eq!(property_value, relation_instance.properties.get(&property_name).unwrap());
598        assert_eq!(extensions, relation_instance.extensions);
599        assert!(relation_instance.has_own_extension(&extension.ty));
600        assert_eq!(extension, relation_instance.get_own_extension(&extension.ty).unwrap());
601    }
602
603    #[test]
604    pub fn create_relation_instance() {
605        let relation_ty = RelationTypeId::random_type_id().unwrap();
606        let instance_id = InstanceId::Id(Uuid::from_str("7839aec8-07ea-41d1-84e5-f00b59d62c3e").unwrap());
607        let relation_instance_ty = RelationInstanceTypeId::new(relation_ty.clone(), instance_id.clone());
608        let outbound_id = Uuid::new_v4();
609        let inbound_id = Uuid::new_v4();
610        let relation_instance_id = RelationInstanceId::builder()
611            .outbound_id(outbound_id)
612            .ty(&relation_instance_ty)
613            .inbound_id(inbound_id)
614            .build();
615        let property_name = r_string();
616        let property_value = json!(r_string());
617        let properties = PropertyInstances::new().property(property_name.clone(), property_value.clone());
618        let relation_instance = RelationInstance::new(
619            relation_instance_id.outbound_id,
620            relation_instance_id.ty,
621            relation_instance_id.inbound_id,
622            PropertyInstances::new().property(&property_name, property_value.clone()),
623        );
624        assert_eq!(outbound_id, relation_instance.outbound_id);
625        assert_eq!(relation_instance_ty, relation_instance.ty);
626        assert_eq!(relation_ty, relation_instance.relation_type_id());
627        assert_eq!(instance_id, relation_instance.instance_id());
628        assert_eq!(inbound_id, relation_instance.inbound_id);
629        assert_eq!(properties, relation_instance.properties);
630        assert_eq!(property_value, relation_instance.properties.get(&property_name).unwrap());
631    }
632
633    #[test]
634    fn relation_instance_typed_getter_test() {
635        let property_name = r_string();
636        let mut i = RelationInstance::new(
637            Uuid::new_v4(),
638            RelationInstanceTypeId::new(RelationTypeId::random_type_id().unwrap(), InstanceId::Id(Uuid::new_v4())),
639            Uuid::new_v4(),
640            PropertyInstances::new().property(&property_name, json!(false)),
641        );
642        i.set(property_name.clone(), json!(true));
643        assert!(i.as_bool(&property_name).unwrap());
644        i.set(property_name.clone(), json!(false));
645        assert!(!i.as_bool(&property_name).unwrap());
646        i.set(property_name.clone(), json!(123));
647        assert_eq!(123, i.as_u64(&property_name).unwrap());
648        i.set(property_name.clone(), json!(-123));
649        assert_eq!(-123, i.as_i64(&property_name).unwrap());
650        i.set(property_name.clone(), json!(1.23));
651        assert_eq!(1.23, i.as_f64(&property_name).unwrap());
652        let s = r_string();
653        i.set(property_name.clone(), json!(s.clone()));
654        assert_eq!(s, i.as_string(&property_name).unwrap());
655        let a = json!([1, 2, 3]);
656        i.set(property_name.clone(), a.clone());
657        assert_eq!(json!(1), i.as_array(&property_name).unwrap().index(0).clone());
658        assert_eq!(json!(2), i.as_array(&property_name).unwrap().index(1).clone());
659        assert_eq!(json!(3), i.as_array(&property_name).unwrap().index(2).clone());
660        let o = json!({
661            "k": "v"
662        });
663        i.set(property_name.clone(), o.clone());
664        assert_eq!(json!("v"), i.as_object(&property_name).unwrap().index("k").clone());
665    }
666
667    #[test]
668    fn relation_instance_deserialize_fully_valid_test() {
669        let outbound_id = Uuid::from_str("13104a11-96d3-4e24-aa87-e4037de7a28e").unwrap();
670        let ty = RelationTypeId::from_str("fully::qualified::namespace::RelationType").unwrap();
671        let instance_id = InstanceId::Id(Uuid::from_str("7839aec8-07ea-41d1-84e5-f00b59d62c3e").unwrap());
672        let inbound_id = Uuid::from_str("0924e83a-52cf-4540-9a21-37cc87150a17").unwrap();
673        let component_ty = ComponentTypeId::from_str("fully::qualified::namespace::Component").unwrap();
674        let extension_ty = ExtensionTypeId::from_str("fully::qualified::namespace::Extension").unwrap();
675        let relation_instance = serde_json::from_str::<RelationInstance>(
676            r#"{
677          "outbound_id": "13104a11-96d3-4e24-aa87-e4037de7a28e",
678          "type": "fully::qualified::namespace::RelationType",
679          "instance_id": "7839aec8-07ea-41d1-84e5-f00b59d62c3e",
680          "inbound_id": "0924e83a-52cf-4540-9a21-37cc87150a17",
681          "description": "d",
682          "components": [
683            "fully::qualified::namespace::Component"
684          ],
685          "properties": {
686            "property_name": "property_value"
687          },
688          "extensions": [
689            {
690              "type": "fully::qualified::namespace::Extension",
691              "extension": ""
692            }
693          ]
694        }"#,
695        )
696        .expect("Failed to deserialize relation instance");
697        assert_eq!(outbound_id, relation_instance.outbound_id);
698        assert_eq!(ty, relation_instance.ty.relation_type_id());
699        assert_eq!(instance_id, relation_instance.ty.instance_id());
700        assert_eq!(inbound_id, relation_instance.inbound_id);
701        assert_eq!("d", relation_instance.description);
702        assert_eq!(1, relation_instance.components.len());
703        assert!(relation_instance.is_a(&component_ty));
704        assert_eq!(1, relation_instance.properties.len());
705        assert_eq!("property_value", relation_instance.get("property_name").unwrap());
706        assert_eq!(1, relation_instance.extensions.len());
707        assert!(relation_instance.get_own_extension(&extension_ty).is_some());
708    }
709
710    #[test]
711    fn relation_instance_ser_test() {
712        let relation_instance = RelationInstance::random_instance().unwrap();
713        println!("{}", serde_json::to_string_pretty(&relation_instance).expect("Failed to serialize relation instance"));
714    }
715
716    #[test]
717    fn relation_instance_json_schema() {
718        let schema = schema_for!(RelationInstance);
719        println!("{}", serde_json::to_string_pretty(&schema).unwrap());
720    }
721}