lexa_framework/database/
model.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
3// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
4// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
5// ┃                                                                           ┃
6// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
7// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
8// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
9// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
10
11#[cfg(feature = "database-postgres")]
12mod postgres;
13
14#[cfg(feature = "database-postgres")]
15pub use self::postgres::ModelPostgresInterface;
16use super::error::Error;
17
18// --------- //
19// Interface //
20// --------- //
21
22#[async_trait::async_trait]
23pub trait ModelInterface {
24	/// Base de donnée.
25	type Database: lexa_database::SGBD;
26
27	/// Entité du modèle.
28	type Entity: Unpin
29		+ Send
30		+ Sync
31		+ serde::ser::Serialize
32		+ serde::de::DeserializeOwned;
33
34	/// Crée une instance du [model](Self).
35	fn new(database: &Self::Database) -> Self
36	where
37		Self: Sized;
38
39	fn database(&self) -> &Self::Database;
40
41	/// Nom de la table du model, correspondant à un nom de table d'une base de
42	/// données.
43	fn table() -> &'static str;
44
45	/// Tous les champs d'une entité.
46	fn fields() -> &'static [&'static str];
47
48	/// Récupère tous les résultats de la table [Self::table()].
49	async fn fetch_all<'c>(&self) -> Result<Vec<Self::Entity>, Error>;
50
51	/// Récupère tous les résultats de la table [Self::table()] en fonction d'un
52	/// ID.
53	async fn fetch_all_by_id(
54		&self,
55		id: impl ToString + Send + Sync,
56	) -> Result<Vec<Self::Entity>, Error>;
57
58	/// Cherche dans la table de la base de donnée s'il existe l'ID passé en
59	/// argument. En supposant qu'il existe un champ `id` dans la table.
60	async fn find_by_id(
61		&self,
62		id: impl ToString + Send + Sync,
63	) -> Result<Self::Entity, Error>;
64
65	/// Ajoute une entité en base de données.
66	async fn create(
67		&self,
68		data: impl serde::ser::Serialize + Send + Sync,
69	) -> Result<Self::Entity, Error>;
70
71	/// Supprime une entité en base de données en fonction d'un ID.
72	async fn delete_by_id(
73		&self,
74		id: impl ToString + Send + Sync,
75	) -> Result<(), Error>;
76
77	/// Modifie les champs d'une table en base de données.
78	async fn update_by_id(
79		&self,
80		id: impl ToString + Send + Sync,
81		data: impl serde::ser::Serialize + Send + Sync,
82	) -> Result<Self::Entity, Error>;
83}