wb_cache/test/simulation/db/entity/
order.rs

1use std::fmt::Debug;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use fieldx_plus::fx_plus;
6use sea_orm::entity::prelude::*;
7use sea_orm::IntoActiveModel;
8use serde::Deserialize;
9use serde::Serialize;
10
11use crate::test::simulation::db::cache::CacheUpdates;
12use crate::test::simulation::db::cache::DBProvider;
13use crate::test::simulation::db::cache::DCCommon;
14use crate::test::simulation::types::OrderStatus;
15use crate::test::simulation::types::Result;
16use crate::test::simulation::types::SimErrorAny;
17use crate::types::DataControllerResponse;
18use crate::update_iterator::UpdateIterator;
19use crate::DataController;
20
21#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
22#[serde(deny_unknown_fields)]
23#[sea_orm(table_name = "orders")]
24pub struct Model {
25    #[sea_orm(primary_key, auto_increment = false)]
26    #[serde(rename = "i")]
27    pub id:           Uuid,
28    #[serde(rename = "c")]
29    pub customer_id:  i32,
30    #[serde(rename = "p")]
31    pub product_id:   i32,
32    // Order size in items.
33    #[serde(rename = "q")]
34    pub quantity:     i32,
35    /// The current status of the order.
36    #[serde(rename = "s")]
37    pub status:       OrderStatus,
38    /// The day number when the order was placed.
39    #[serde(rename = "d")]
40    pub purchased_on: i32,
41}
42
43#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
44pub enum Relation {
45    #[sea_orm(
46        belongs_to = "super::customer::Entity",
47        from = "Column::CustomerId",
48        to = "super::customer::Column::Id"
49    )]
50    Customer,
51    #[sea_orm(
52        belongs_to = "super::product::Entity",
53        from = "Column::ProductId",
54        to = "super::product::Column::Id"
55    )]
56    Product,
57}
58
59impl ActiveModelBehavior for ActiveModel {}
60
61#[fx_plus(
62    child(DBCP, unwrap(or_else(SimErrorAny, super::dbcp_gone("order manager")))),
63    sync,
64    rc
65)]
66
67/// The manager and data controller for the order model.
68pub struct Manager<DBCP>
69where
70    DBCP: DBProvider, {}
71
72impl<DBCP> Manager<DBCP>
73where
74    DBCP: DBProvider,
75{
76    /// Get the order for the given ID.
77    pub async fn get_by_order_id(&self, order_id: Uuid) -> Result<Vec<Model>, SimErrorAny> {
78        Ok(Entity::find()
79            .filter(Column::Id.eq(order_id))
80            .all(&self.db_provider()?.db_connection()?)
81            .await?)
82    }
83}
84
85impl<DBCP> Debug for Manager<DBCP>
86where
87    DBCP: DBProvider,
88{
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        write!(f, "OrderManager")
91    }
92}
93
94#[async_trait]
95impl<DBCP> DataController for Manager<DBCP>
96where
97    DBCP: DBProvider,
98{
99    type CacheUpdate = CacheUpdates<ActiveModel>;
100    type Error = SimErrorAny;
101    type Key = Uuid;
102    type Value = Model;
103
104    async fn get_for_key(&self, id: &Self::Key) -> Result<Option<Self::Value>> {
105        Ok(Entity::find_by_id(*id)
106            .one(&self.db_provider()?.db_connection()?)
107            .await?)
108    }
109
110    fn primary_key_of(&self, value: &Self::Value) -> Self::Key {
111        value.id
112    }
113
114    async fn write_back(&self, update_records: Arc<UpdateIterator<Self>>) -> Result<()> {
115        self.wbdc_write_back(update_records).await
116    }
117
118    async fn on_new(&self, key: &Self::Key, value: &Self::Value) -> Result<DataControllerResponse<Self>> {
119        self.wbdbc_on_new(key, &value.clone().into_active_model()).await
120    }
121
122    async fn on_delete(
123        &self,
124        key: &Self::Key,
125        update: Option<&CacheUpdates<ActiveModel>>,
126    ) -> Result<DataControllerResponse<Self>> {
127        self.wbdc_on_delete(key, update).await
128    }
129
130    async fn on_change(
131        &self,
132        key: &Self::Key,
133        value: &Self::Value,
134        old_value: Self::Value,
135        prev_update: Option<Self::CacheUpdate>,
136    ) -> Result<DataControllerResponse<Self>> {
137        self.wbdc_on_change(key, value, old_value, prev_update).await
138    }
139}
140
141impl<DBCP> DCCommon<Entity, DBCP, true> for Manager<DBCP>
142where
143    DBCP: DBProvider,
144{
145    fn delete_many_condition(dm: sea_orm::DeleteMany<Entity>, keys: Vec<Self::Key>) -> sea_orm::DeleteMany<Entity> {
146        dm.filter(Column::Id.is_in(keys))
147    }
148}