ash_domain/attribute.rs
1//! Attributes: the typed fields that make up a [`Resource`](crate::Resource).
2//!
3//! Attributes are pure metadata. Their introspection (`resource.attributes()`)
4//! is the seam every extension reads — an API generator, an admin UI, or a
5//! database-backed data layer all work purely from the declared attributes.
6//!
7//! An attribute is minimal: a `name`, a [`ty`](Attribute::ty), and an optional
8//! `default`. A scalar's type **is** its Rust type — [`AttrType::Scalar`] carries
9//! a [`TypeId`], produced from the field's own type
10//! (`Attribute::scalar::<T>`, or inferred by `#[derive(Resource)]`). The core
11//! neither generates ids by type, stamps timestamps, nor maps storage columns:
12//! those are consumer concerns (an [`IdGenerator`](crate::IdGenerator), a
13//! [`Change`](crate::action::Change), a [`DataLayer`](crate::DataLayer)).
14
15use std::any::TypeId;
16
17use crate::value::Value;
18
19/// The type of an [`Attribute`].
20///
21/// A scalar carries its **Rust type** rather than a framework-defined primitive;
22/// the three underscore-prefixed variants are the framework-relational kinds
23/// (a reference, an embed, a repeated embed).
24// Not `Eq`: an embed's carried attributes can hold a `Value::Float` default,
25// and float equality is only `PartialEq`.
26#[derive(Clone, Debug, PartialEq)]
27pub enum AttrType {
28 /// A scalar value, typed by its Rust type. `type_id` is the identity used
29 /// for any type dispatch; `name` is [`type_name`](std::any::type_name) for
30 /// diagnostics. Build with [`AttrType::scalar`] / [`Attribute::scalar`].
31 Scalar {
32 /// The [`TypeId`] of the scalar's Rust type.
33 type_id: TypeId,
34 /// `std::any::type_name::<T>()`, for diagnostics only.
35 name: &'static str,
36 },
37 /// A reference to another resource (by name) — the storage side of a
38 /// relationship.
39 _Ref(String),
40 /// An **embedded resource**: a structured value stored *inside* the parent
41 /// (in one column, as a [`Value::Map`]), not in a table of
42 /// its own. Carries the embedded resource's own attributes inline, so the
43 /// write pipeline applies their declared defaults to the nested value — the
44 /// embedded shape is known, not opaque.
45 _Embed(Vec<Attribute>),
46 /// A repeated embedded resource: a [`Value::List`] of
47 /// [`Map`](crate::Value::Map)s, each carrying the embedded attributes.
48 _EmbedList(Vec<Attribute>),
49}
50
51impl AttrType {
52 /// A [`Scalar`](AttrType::Scalar) for the Rust type `T`.
53 pub fn scalar<T: 'static>() -> Self {
54 AttrType::Scalar {
55 type_id: TypeId::of::<T>(),
56 name: std::any::type_name::<T>(),
57 }
58 }
59}
60
61/// A named, typed field of a resource.
62#[derive(Clone, Debug, PartialEq)]
63pub struct Attribute {
64 /// The attribute name.
65 pub name: String,
66 /// Its type.
67 pub ty: AttrType,
68 /// A default applied on create when the value is absent.
69 pub default: Option<Value>,
70}
71
72impl Attribute {
73 /// Declare a plain attribute with `name` and `ty`: no default.
74 ///
75 /// This is a base to refine with struct-update syntax — the Rust way, in
76 /// place of a builder chain. Set the fields you want and inherit the rest:
77 ///
78 /// ```
79 /// use ash_domain::attribute::{Attribute, AttrType};
80 /// use ash_domain::Value;
81 ///
82 /// // A string primary key (identified by name via `Resource::primary_key`,
83 /// // not by any flag on the attribute).
84 /// let id = Attribute::scalar::<String>("id");
85 ///
86 /// // A bool with a default.
87 /// let done = Attribute {
88 /// default: Some(Value::Bool(false)),
89 /// ..Attribute::scalar::<bool>("done")
90 /// };
91 /// # let _ = (id, done);
92 /// ```
93 ///
94 /// The core validates none of these values on write — presence, ranges, and
95 /// formats are enforced by a [`Validation`](crate::action::Validation)
96 /// registered on the action, not by attribute metadata.
97 pub fn new(name: impl Into<String>, ty: AttrType) -> Self {
98 Self {
99 name: name.into(),
100 ty,
101 default: None,
102 }
103 }
104
105 /// A scalar attribute of Rust type `T` — shorthand for
106 /// `Attribute::new(name, AttrType::scalar::<T>())`.
107 pub fn scalar<T: 'static>(name: impl Into<String>) -> Self {
108 Self::new(name, AttrType::scalar::<T>())
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115
116 #[test]
117 fn scalar_carries_its_rust_type() {
118 let a = Attribute::scalar::<String>("owner");
119 assert_eq!(a.name, "owner");
120 assert_eq!(
121 a.ty,
122 AttrType::Scalar {
123 type_id: TypeId::of::<String>(),
124 name: std::any::type_name::<String>(),
125 }
126 );
127 }
128
129 #[test]
130 fn distinct_rust_types_are_distinct_scalars() {
131 assert_ne!(
132 Attribute::scalar::<String>("x").ty,
133 Attribute::scalar::<i64>("x").ty
134 );
135 }
136}