Skip to main content

rust_eloquent/
lib.rs

1use sqlx::{AnyPool, any::install_default_drivers};
2use std::sync::OnceLock;
3
4// Re-export the procedural macro so users only need to import `rust-eloquent`
5pub use rust_eloquent_macros::Eloquent;
6
7// Re-export async_trait so the macro can use it implicitly
8pub use async_trait::async_trait;
9
10// Re-export sqlx and FromRow for database mapping
11pub use sqlx;
12pub use sqlx::FromRow;
13
14/// The global connection pool
15static DB_POOL: OnceLock<AnyPool> = OnceLock::new();
16
17/// The driver identifier (postgres, mysql, sqlite) to help macro syntax formatting
18static DB_DRIVER: OnceLock<String> = OnceLock::new();
19
20/// Enum dinĂ¢mico para encapsular qualquer tipo que possa ser associado ao banco de dados pelo Macro
21#[derive(Clone, Debug)]
22pub enum EloquentValue {
23    String(String),
24    Int(i32),
25    Float(f64),
26    Bool(bool),
27}
28
29impl From<&str> for EloquentValue {
30    fn from(s: &str) -> Self { EloquentValue::String(s.to_string()) }
31}
32impl From<String> for EloquentValue {
33    fn from(s: String) -> Self { EloquentValue::String(s) }
34}
35impl From<i32> for EloquentValue {
36    fn from(i: i32) -> Self { EloquentValue::Int(i) }
37}
38impl From<f64> for EloquentValue {
39    fn from(f: f64) -> Self { EloquentValue::Float(f) }
40}
41impl From<bool> for EloquentValue {
42    fn from(b: bool) -> Self { EloquentValue::Bool(b) }
43}
44
45/// Eloquent configuration structure
46pub struct Eloquent;
47
48impl Eloquent {
49    /// Initialize the global database connection pool using an agnostic URI
50    pub async fn init(database_url: &str) -> Result<(), sqlx::Error> {
51        install_default_drivers();
52        let pool = AnyPool::connect(database_url).await?;
53        
54        if DB_POOL.set(pool).is_err() {
55            panic!("Eloquent has already been initialized");
56        }
57
58        let driver = if database_url.starts_with("postgres") {
59            "postgres"
60        } else if database_url.starts_with("mysql") {
61            "mysql"
62        } else {
63            "sqlite"
64        };
65        
66        let _ = DB_DRIVER.set(driver.to_string());
67        
68        Ok(())
69    }
70
71    /// Retrieve the global database connection pool
72    pub fn pool() -> &'static AnyPool {
73        DB_POOL.get().expect("Eloquent must be initialized before querying")
74    }
75
76    /// Retrieve the active driver string
77    pub fn driver() -> &'static str {
78        DB_DRIVER.get().expect("Eloquent must be initialized before querying").as_str()
79    }
80}
81
82/// The core trait that all Eloquent models will implement via #[derive(Eloquent)]
83#[async_trait]
84pub trait EloquentModel {
85    fn table_name() -> &'static str;
86}