teo_runtime/model/
ctx.rs

1use key_path::path;
2use crate::value::Value;
3use crate::connection::transaction;
4use crate::model;
5use crate::model::Model;
6
7#[derive(Clone)]
8pub struct Ctx {
9    transaction_ctx: transaction::Ctx,
10    model: Model,
11}
12
13impl Ctx {
14
15    pub fn new(transaction_ctx: transaction::Ctx, model: &Model) -> Self {
16        Self {
17            transaction_ctx,
18            model: model.clone(),
19        }
20    }
21
22    pub async fn find_unique<T: From<model::Object>>(&self, finder: &Value) -> teo_result::Result<Option<T>> {
23        self.transaction_ctx.find_unique(&self.model, finder, None, path![]).await
24    }
25
26    pub async fn find_first<T: From<model::Object>>(&self, finder: &Value) -> teo_result::Result<Option<T>> {
27        self.transaction_ctx.find_first(&self.model, finder, None, path![]).await
28    }
29
30    pub async fn find_many<T: From<model::Object>>(&self, finder: &Value) -> teo_result::Result<Vec<T>> {
31        self.transaction_ctx.find_many(&self.model, finder, None, path![]).await
32    }
33
34    pub async fn count(&self, finder: &Value) -> teo_result::Result<Value> {
35        self.transaction_ctx.count(&self.model, finder, path![]).await
36    }
37
38    pub async fn count_objects(&self, finder: &Value) -> teo_result::Result<usize> {
39        self.transaction_ctx.count_objects(&self.model, finder, path![]).await
40    }
41
42    pub async fn count_fields<T, E>(&self, finder: &Value) -> teo_result::Result<T> where T: TryFrom<Value, Error=E>, teo_result::Error: From<E> {
43        self.transaction_ctx.count_fields(&self.model, finder, path![]).await
44    }
45
46    pub async fn aggregate<T, E>(&self, finder: &Value) -> teo_result::Result<T> where T: TryFrom<Value, Error=E>, teo_result::Error: From<E> {
47        Ok(self.transaction_ctx.aggregate(&self.model, finder, path![]).await?.try_into()?)
48    }
49
50    pub async fn group_by<T, E>(&self, finder: &Value) -> teo_result::Result<Vec<T>> where T: TryFrom<Value, Error=E>, teo_result::Error: From<E> {
51        Ok(self.transaction_ctx.group_by(&self.model, finder, path![]).await?.into_iter().map(|t| T::try_from(t)).collect::<Result<Vec<T>, E>>()?)
52    }
53
54    pub async fn sql<T, E>(&self, sql: &str) -> teo_result::Result<Vec<T>> where T: TryFrom<Value, Error=E>, teo_result::Error: From<E> {
55        self.transaction_ctx.sql(&self.model, sql).await
56    }
57
58    pub async fn create_object<T>(&self, input: &Value) -> teo_result::Result<T> where T: From<model::Object> {
59        Ok(self.transaction_ctx.create_object(&self.model, input, None).await?.into())
60    }
61
62    pub fn transaction_ctx(&self) -> &transaction::Ctx {
63        &self.transaction_ctx
64    }
65
66    pub fn model(&self) -> &Model {
67        &self.model
68    }
69}