sylvia_iot_broker/models/
model_sqlite.rs

1//! Pure SQLite model.
2
3use std::{error::Error as StdError, sync::Arc};
4
5use async_trait::async_trait;
6use sqlx::SqlitePool;
7
8use super::{
9    application, device, device_route, dldata_buffer, network, network_route,
10    sqlite::{
11        application::Model as ApplicationModel,
12        conn::{self, Options},
13        device::Model as DeviceModel,
14        device_route::Model as DeviceRouteModel,
15        dldata_buffer::Model as DlDataBufferModel,
16        network::Model as NetworkModel,
17        network_route::Model as NetworkRouteModel,
18        unit::Model as UnitModel,
19    },
20    unit,
21};
22
23/// Pure SQLite model.
24#[derive(Clone)]
25pub struct Model {
26    conn: Arc<SqlitePool>,
27    unit: Arc<UnitModel>,
28    application: Arc<ApplicationModel>,
29    network: Arc<NetworkModel>,
30    device: Arc<DeviceModel>,
31    device_route: Arc<DeviceRouteModel>,
32    network_route: Arc<NetworkRouteModel>,
33    dldata_buffer: Arc<DlDataBufferModel>,
34}
35
36impl Model {
37    /// Create an instance.
38    pub async fn new(opts: &Options) -> Result<Self, Box<dyn StdError>> {
39        let conn = Arc::new(conn::connect(opts).await?);
40        Ok(Model {
41            conn: conn.clone(),
42            unit: Arc::new(UnitModel::new(conn.clone()).await?),
43            application: Arc::new(ApplicationModel::new(conn.clone()).await?),
44            network: Arc::new(NetworkModel::new(conn.clone()).await?),
45            device: Arc::new(DeviceModel::new(conn.clone()).await?),
46            device_route: Arc::new(DeviceRouteModel::new(conn.clone()).await?),
47            network_route: Arc::new(NetworkRouteModel::new(conn.clone()).await?),
48            dldata_buffer: Arc::new(DlDataBufferModel::new(conn.clone()).await?),
49        })
50    }
51
52    /// Get the raw database connection ([`SqlitePool`]).
53    pub fn get_connection(&self) -> &SqlitePool {
54        &self.conn
55    }
56}
57
58#[async_trait]
59impl super::Model for Model {
60    async fn close(&self) -> Result<(), Box<dyn StdError>> {
61        Ok(())
62    }
63
64    fn unit(&self) -> &dyn unit::UnitModel {
65        self.unit.as_ref()
66    }
67
68    fn application(&self) -> &dyn application::ApplicationModel {
69        self.application.as_ref()
70    }
71
72    fn network(&self) -> &dyn network::NetworkModel {
73        self.network.as_ref()
74    }
75
76    fn device(&self) -> &dyn device::DeviceModel {
77        self.device.as_ref()
78    }
79
80    fn device_route(&self) -> &dyn device_route::DeviceRouteModel {
81        self.device_route.as_ref()
82    }
83
84    fn network_route(&self) -> &dyn network_route::NetworkRouteModel {
85        self.network_route.as_ref()
86    }
87
88    fn dldata_buffer(&self) -> &dyn dldata_buffer::DlDataBufferModel {
89        self.dldata_buffer.as_ref()
90    }
91}