Skip to main content

ormkit/
entity.rs

1//! Core Entity trait for ORM models
2//!
3//! All models that can be stored in the database must implement this trait.
4//! It provides the foundation for ORM operations like queries, inserts, and updates.
5
6use crate::query::typed::TypedQueryBuilder;
7use std::fmt::{Debug, Display};
8
9/// Core entity trait that all database models must implement
10pub trait Entity: Sized + Send + Sync + Debug + Display {
11    /// The ID type for this entity (e.g., Uuid, i64)
12    type Id: Copy + PartialEq + Debug + Display + Send + Sync + 'static;
13
14    /// The table name in the database
15    fn table_name() -> &'static str;
16
17    /// Get the entity's ID
18    fn id(&self) -> Self::Id;
19
20    /// Start building a type-safe query for this entity
21    ///
22    /// # Example
23    ///
24    /// ```rust,no_run
25    /// # use ormkit::Entity;
26    /// # #[derive(ormkit::Entity)]
27    /// # #[ormkit(table = "users")]
28    /// # struct User { #[ormkit(id)] id: uuid::Uuid, email: String }
29    /// # async fn test(pool: &sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
30    /// let users = User::query()
31    ///     .filter(User::email().eq("user@example.com"))
32    ///     .fetch_all(pool)
33    ///     .await?;
34    /// # Ok(()) }
35    /// ```
36    fn query() -> TypedQueryBuilder<Self> {
37        TypedQueryBuilder::new()
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    // Mock entity for testing
46    #[derive(Debug)]
47    struct TestEntity {
48        id: String,
49        name: String,
50    }
51
52    impl Entity for TestEntity {
53        type Id = String;
54
55        fn table_name() -> &'static str {
56            "test_entities"
57        }
58
59        fn id(&self) -> Self::Id {
60            self.id
61        }
62    }
63}