navree_orm/attributes/
model_ref.rs1use std::fmt;
25use std::marker::PhantomData;
26
27use serde::{Deserialize, Serialize};
28
29use crate::collection::Collection;
30use crate::error::{OrmError, Result};
31use crate::exec::{Access, Executor};
32use crate::model::{Model, PrimaryKey};
33use crate::query::Builder;
34use crate::record::Record;
35use crate::value::{Field, to_json};
36
37#[derive(Serialize, Deserialize)]
40#[serde(bound = "")]
41pub struct ModelRef<M> {
42 model: String,
43 key: serde_json::Value,
44 #[serde(default, skip_serializing_if = "Vec::is_empty")]
45 relations: Vec<String>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
47 connection: Option<String>,
48 #[serde(skip)]
49 _model: PhantomData<fn() -> M>,
50}
51
52#[derive(Serialize, Deserialize)]
55#[serde(bound = "")]
56pub struct ModelRefs<M> {
57 model: String,
58 keys: Vec<serde_json::Value>,
59 #[serde(default, skip_serializing_if = "Vec::is_empty")]
60 relations: Vec<String>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 connection: Option<String>,
63 #[serde(skip)]
64 _model: PhantomData<fn() -> M>,
65}
66
67fn check_model<M: Model>(model: &str) -> Result<()> {
68 if model == M::meta().name() {
69 Ok(())
70 } else {
71 Err(OrmError::InvalidQuery(format!(
72 "this reference names model {model}, not {}",
73 M::meta().name()
74 )))
75 }
76}
77
78fn key_from<M: Model>(json: &serde_json::Value) -> Result<M::Key> {
79 M::Key::from_json(json.clone()).map_err(|error| OrmError::Decode {
80 model: M::meta().name().into(),
81 column: M::meta().key_column().to_owned(),
82 expected: M::Key::type_name(),
83 message: format!("the reference's key {json}: {error}"),
84 })
85}
86
87impl<M: Model> ModelRef<M> {
88 pub fn of(record: &Record<M>) -> Result<Self> {
90 if !record.exists() {
91 return Err(Record::<M>::not_persisted("refer to"));
92 }
93 Ok(ModelRef {
94 model: M::meta().name().to_owned(),
95 key: to_json(&record.key().to_value()),
96 relations: record.relations().names().map(str::to_owned).collect(),
97 connection: M::meta().connection_name().map(str::to_owned),
98 _model: PhantomData,
99 })
100 }
101
102 pub fn model_name(&self) -> &str {
104 &self.model
105 }
106
107 pub fn key(&self) -> Result<M::Key> {
109 check_model::<M>(&self.model)?;
110 key_from::<M>(&self.key)
111 }
112
113 pub fn relations(&self) -> &[String] {
116 &self.relations
117 }
118
119 pub fn connection(&self) -> Option<&str> {
121 self.connection.as_deref()
122 }
123
124 pub async fn restore<E: Executor + ?Sized>(&self, exec: &E) -> Result<Record<M>> {
129 let key = self.key()?;
130 self.restore_or_skip(exec)
131 .await?
132 .ok_or_else(|| OrmError::not_found(M::meta().name(), vec![key.to_key_string()]))
133 }
134
135 pub async fn restore_or_skip<E: Executor + ?Sized>(
138 &self,
139 exec: &E,
140 ) -> Result<Option<Record<M>>> {
141 let key = self.key()?;
142 let target = exec.target(Access::Write).await?;
143 Ok(Builder::<M>::new()
144 .without_global_scopes()
145 .where_key(key)
146 .limit(1)
147 .fetch(&target)
148 .await?
149 .into_vec()
150 .into_iter()
151 .next())
152 }
153}
154
155impl<M: Model> ModelRefs<M> {
156 pub fn of(records: &Collection<M>) -> Result<Self> {
158 let mut keys = Vec::with_capacity(records.len());
159 let mut relations: Vec<String> = Vec::new();
160 for record in records.iter() {
161 if !record.exists() {
162 return Err(Record::<M>::not_persisted("refer to"));
163 }
164 keys.push(to_json(&record.key().to_value()));
165 for name in record.relations().names() {
166 if !relations.iter().any(|known| known == name) {
167 relations.push(name.to_owned());
168 }
169 }
170 }
171 Ok(ModelRefs {
172 model: M::meta().name().to_owned(),
173 keys,
174 relations,
175 connection: M::meta().connection_name().map(str::to_owned),
176 _model: PhantomData,
177 })
178 }
179
180 pub fn model_name(&self) -> &str {
182 &self.model
183 }
184
185 pub fn keys(&self) -> Result<Vec<M::Key>> {
187 check_model::<M>(&self.model)?;
188 self.keys.iter().map(key_from::<M>).collect()
189 }
190
191 pub fn len(&self) -> usize {
193 self.keys.len()
194 }
195
196 pub fn is_empty(&self) -> bool {
198 self.keys.is_empty()
199 }
200
201 pub fn relations(&self) -> &[String] {
203 &self.relations
204 }
205
206 pub fn connection(&self) -> Option<&str> {
208 self.connection.as_deref()
209 }
210
211 pub async fn restore<E: Executor + ?Sized>(&self, exec: &E) -> Result<Collection<M>> {
215 let keys = self.keys()?;
216 if keys.is_empty() {
217 return Ok(Collection::new());
218 }
219 let target = exec.target(Access::Write).await?;
220 let mut found = Builder::<M>::new()
221 .without_global_scopes()
222 .where_key_in(keys.clone())
223 .fetch(&target)
224 .await?
225 .into_vec();
226 let mut ordered = Vec::with_capacity(found.len());
227 for key in keys {
228 if let Some(index) = found.iter().position(|record| record.key() == key) {
229 ordered.push(found.swap_remove(index));
230 }
231 }
232 Ok(ordered.into())
233 }
234}
235
236impl<M: Model> Record<M> {
237 pub fn to_ref(&self) -> Result<ModelRef<M>> {
239 ModelRef::of(self)
240 }
241}
242
243impl<M: Model> Collection<M> {
244 pub fn to_refs(&self) -> Result<ModelRefs<M>> {
246 ModelRefs::of(self)
247 }
248}
249
250impl<M> Clone for ModelRef<M> {
251 fn clone(&self) -> Self {
252 ModelRef {
253 model: self.model.clone(),
254 key: self.key.clone(),
255 relations: self.relations.clone(),
256 connection: self.connection.clone(),
257 _model: PhantomData,
258 }
259 }
260}
261
262impl<M> Clone for ModelRefs<M> {
263 fn clone(&self) -> Self {
264 ModelRefs {
265 model: self.model.clone(),
266 keys: self.keys.clone(),
267 relations: self.relations.clone(),
268 connection: self.connection.clone(),
269 _model: PhantomData,
270 }
271 }
272}
273
274impl<M> PartialEq for ModelRef<M> {
275 fn eq(&self, other: &Self) -> bool {
276 self.model == other.model
277 && self.key == other.key
278 && self.relations == other.relations
279 && self.connection == other.connection
280 }
281}
282
283impl<M> PartialEq for ModelRefs<M> {
284 fn eq(&self, other: &Self) -> bool {
285 self.model == other.model
286 && self.keys == other.keys
287 && self.relations == other.relations
288 && self.connection == other.connection
289 }
290}
291
292impl<M> fmt::Debug for ModelRef<M> {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 f.debug_struct("ModelRef")
295 .field("model", &self.model)
296 .field("key", &self.key)
297 .field("relations", &self.relations)
298 .field("connection", &self.connection)
299 .finish()
300 }
301}
302
303impl<M> fmt::Debug for ModelRefs<M> {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 f.debug_struct("ModelRefs")
306 .field("model", &self.model)
307 .field("keys", &self.keys)
308 .field("relations", &self.relations)
309 .field("connection", &self.connection)
310 .finish()
311 }
312}