1use sqlx::{AnyPool, any::install_default_drivers};
2use std::sync::OnceLock;
3
4pub use rust_eloquent_macros::Eloquent;
6
7pub use async_trait::async_trait;
9
10pub use sqlx;
12pub use sqlx::FromRow;
13
14static DB_POOL: OnceLock<AnyPool> = OnceLock::new();
16
17static DB_DRIVER: OnceLock<String> = OnceLock::new();
19
20#[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
45pub struct Eloquent;
47
48impl Eloquent {
49 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 pub fn pool() -> &'static AnyPool {
73 DB_POOL.get().expect("Eloquent must be initialized before querying")
74 }
75
76 pub fn driver() -> &'static str {
78 DB_DRIVER.get().expect("Eloquent must be initialized before querying").as_str()
79 }
80}
81
82#[async_trait]
84pub trait EloquentModel {
85 fn table_name() -> &'static str;
86}