1use std::collections::{BTreeMap, BTreeSet};
2
3use crate::{
4 CompactRow, Decimal, EntityDescriptor, EntitySnapshot, MutationValues, Value,
5 record_to_json_value,
6};
7
8pub trait TeaqlEntity {
9 const ENTITY_NAME: &'static str;
10
11 fn entity_descriptor() -> EntityDescriptor;
12
13 fn register_into(store: &mut impl EntityDescriptorStore) {
14 store.register_descriptor(Self::entity_descriptor());
15 }
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct EntityError {
20 pub entity: String,
21 pub message: String,
22}
23
24impl EntityError {
25 pub fn new(entity: impl Into<String>, message: impl Into<String>) -> Self {
26 Self {
27 entity: entity.into(),
28 message: message.into(),
29 }
30 }
31}
32
33impl std::fmt::Display for EntityError {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 write!(f, "{}: {}", self.entity, self.message)
36 }
37}
38
39impl std::error::Error for EntityError {}
40
41pub trait Entity: TeaqlEntity + Sized {
42 fn from_compact_row(row: CompactRow) -> Result<Self, EntityError>;
43
44 fn from_compact_row_with_context(
45 row: CompactRow,
46 context: &dyn std::any::Any,
47 ) -> Result<Self, EntityError> {
48 let mut entity = Self::from_compact_row(row)?;
49 entity.on_loaded(context);
50 Ok(entity)
51 }
52
53 fn into_values(self) -> MutationValues;
54
55 fn is_field_loaded(&self, _field: &str) -> bool {
59 true
60 }
61
62 fn set_checker_loaded_fields(&mut self, _fields: BTreeSet<String>) {}
65
66 fn set_checker_dirty_fields(&mut self, _fields: BTreeSet<String>, _values: &MutationValues) {}
70
71 fn dirty_fields(&self) -> Option<BTreeSet<String>> {
75 None
76 }
77
78 fn is_marked_as_delete(&self) -> bool {
80 false
81 }
82
83 fn is_new(&self) -> bool {
85 false
86 }
87
88 fn mark_as_new(&mut self) {}
90
91 fn get_comment(&self) -> Option<String> {
93 None
94 }
95
96 fn set_comment(&mut self, _comment: String) {}
98
99 fn audit_as(self, comment: impl Into<String>) -> Audited<Self> {
102 Audited::new(self, comment)
103 }
104
105 fn original_values(&self) -> Option<EntitySnapshot> {
107 None
108 }
109
110 #[allow(unused_variables)]
113 fn on_loaded(&mut self, context: &dyn std::any::Any) {}
114
115 fn into_json(self) -> serde_json::Value {
116 let values: BTreeMap<String, Value> = self.into_values().into();
117 record_to_json_value(&values)
118 }
119}
120
121pub struct Audited<T: Entity> {
125 inner: T,
126 comment: String,
127}
128
129impl<T: Entity> Audited<T> {
130 pub fn new(entity: T, comment: impl Into<String>) -> Self {
132 let comment = comment.into();
133 assert!(
134 !comment.trim().is_empty(),
135 "audit comment must not be empty"
136 );
137 Self {
138 inner: entity,
139 comment,
140 }
141 }
142
143 pub fn entity(&self) -> &T {
145 &self.inner
146 }
147
148 pub fn entity_mut(&mut self) -> &mut T {
150 &mut self.inner
151 }
152
153 pub fn into_entity(self) -> T {
155 let mut entity = self.inner;
156 entity.set_comment(self.comment);
157 entity
158 }
159
160 pub fn get_comment(&self) -> &str {
162 &self.comment
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Default)]
167pub struct BaseEntityData {
168 pub id: u64,
169 pub version: i64,
170 pub dynamic: BTreeMap<String, Value>,
171}
172
173impl BaseEntityData {
174 pub fn new() -> Self {
175 Self::default()
176 }
177
178 pub fn with_id(mut self, id: u64) -> Self {
179 self.id = id;
180 self
181 }
182
183 pub fn with_version(mut self, version: i64) -> Self {
184 self.version = version;
185 self
186 }
187
188 pub fn with_dynamic(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
189 self.dynamic.insert(key.into(), value.into());
190 self
191 }
192
193 pub fn dynamic(&self, key: &str) -> Option<&Value> {
194 self.dynamic.get(key)
195 }
196
197 pub fn dynamic_i64(&self, key: &str) -> Option<i64> {
198 self.dynamic(key).and_then(Value::try_i64)
199 }
200
201 pub fn dynamic_u64(&self, key: &str) -> Option<u64> {
202 self.dynamic(key).and_then(Value::try_u64)
203 }
204
205 pub fn dynamic_decimal(&self, key: &str) -> Option<Decimal> {
206 self.dynamic(key).and_then(Value::try_decimal)
207 }
208
209 pub fn dynamic_f64(&self, key: &str) -> Option<f64> {
210 self.dynamic(key).and_then(Value::try_f64)
211 }
212
213 pub fn dynamic_text(&self, key: &str) -> Option<&str> {
214 self.dynamic(key).and_then(Value::try_text)
215 }
216
217 pub fn dynamic_bool(&self, key: &str) -> Option<bool> {
218 self.dynamic(key).and_then(Value::try_bool)
219 }
220
221 pub fn put_dynamic(
222 &mut self,
223 key: impl Into<String>,
224 value: impl Into<Value>,
225 ) -> Option<Value> {
226 self.dynamic.insert(key.into(), value.into())
227 }
228
229 pub fn remove_dynamic(&mut self, key: &str) -> Option<Value> {
230 self.dynamic.remove(key)
231 }
232
233 pub fn to_values_map(&self) -> BTreeMap<String, Value> {
234 let mut values = BTreeMap::new();
235 values.insert("id".to_owned(), Value::U64(self.id));
236 values.insert("version".to_owned(), Value::I64(self.version));
237 for (key, value) in &self.dynamic {
238 values.insert(key.clone(), value.clone());
239 }
240 values
241 }
242
243 pub fn from_values_map(values: &BTreeMap<String, Value>) -> Result<Self, EntityError> {
244 let id = match values.get("id") {
245 Some(Value::U64(v)) => *v,
246 Some(Value::I64(v)) if *v >= 0 => *v as u64,
247 Some(Value::Null) | None => 0,
248 other => {
249 return Err(EntityError::new(
250 "BaseEntity",
251 format!("invalid id field: {other:?}"),
252 ));
253 }
254 };
255
256 let version = match values.get("version") {
257 Some(Value::I64(v)) => *v,
258 Some(Value::Null) | None => 0,
259 other => {
260 return Err(EntityError::new(
261 "BaseEntity",
262 format!("invalid version field: {other:?}"),
263 ));
264 }
265 };
266
267 let dynamic = values
268 .iter()
269 .filter(|(key, _)| key.as_str() != "id" && key.as_str() != "version")
270 .map(|(key, value)| (key.clone(), value.clone()))
271 .collect();
272
273 Ok(Self {
274 id,
275 version,
276 dynamic,
277 })
278 }
279}
280
281pub trait BaseEntity: Entity {
282 fn base(&self) -> &BaseEntityData;
283 fn base_mut(&mut self) -> &mut BaseEntityData;
284
285 fn id(&self) -> u64 {
286 self.base().id
287 }
288
289 fn set_id(&mut self, id: u64) {
290 self.base_mut().id = id;
291 }
292
293 fn version_value(&self) -> i64 {
294 self.base().version
295 }
296
297 fn set_version(&mut self, version: i64) {
298 self.base_mut().version = version;
299 }
300
301 fn dynamic(&self, key: &str) -> Option<&Value> {
302 self.base().dynamic(key)
303 }
304
305 fn dynamic_i64(&self, key: &str) -> Option<i64> {
306 self.base().dynamic_i64(key)
307 }
308
309 fn dynamic_u64(&self, key: &str) -> Option<u64> {
310 self.base().dynamic_u64(key)
311 }
312
313 fn dynamic_decimal(&self, key: &str) -> Option<Decimal> {
314 self.base().dynamic_decimal(key)
315 }
316
317 fn dynamic_f64(&self, key: &str) -> Option<f64> {
318 self.base().dynamic_f64(key)
319 }
320
321 fn dynamic_text(&self, key: &str) -> Option<&str> {
322 self.base().dynamic_text(key)
323 }
324
325 fn dynamic_bool(&self, key: &str) -> Option<bool> {
326 self.base().dynamic_bool(key)
327 }
328
329 fn put_dynamic(&mut self, key: impl Into<String>, value: impl Into<Value>) -> Option<Value> {
330 self.base_mut().put_dynamic(key, value)
331 }
332}
333
334pub trait IdentifiableEntity: Entity {
335 fn id_value(&self) -> Value;
336}
337
338pub trait VersionedEntity: Entity {
339 fn version(&self) -> i64;
340}
341
342pub trait TeaqlBoxedRelations: Sized {
343 fn extend_descriptor(descriptor: &mut EntityDescriptor);
344 fn extract_from_values(values: &CompactRow) -> Result<Self, EntityError>;
345 fn inject_into_values(self, values: &mut BTreeMap<String, Value>);
346}
347
348impl<T: TeaqlBoxedRelations> TeaqlBoxedRelations for Box<T> {
349 fn extend_descriptor(descriptor: &mut EntityDescriptor) {
350 T::extend_descriptor(descriptor);
351 }
352 fn extract_from_values(values: &CompactRow) -> Result<Self, EntityError> {
353 Ok(Box::new(T::extract_from_values(values)?))
354 }
355 fn inject_into_values(self, values: &mut BTreeMap<String, Value>) {
356 (*self).inject_into_values(values);
357 }
358}
359
360pub trait EntityDescriptorStore {
361 fn register_descriptor(&mut self, descriptor: EntityDescriptor);
362}
363
364#[macro_export]
365macro_rules! register_entities {
366 ($store:expr, $($entity:ty),+ $(,)?) => {{
367 $(
368 <$entity as $crate::TeaqlEntity>::register_into($store);
369 )+
370 }};
371}