use super::connection::DatabasePool;
use super::orm::QueryBuilder;
use async_trait::async_trait;
#[async_trait]
pub trait Model:
Sized + Send + Sync + for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Unpin
{
const TABLE: &'static str;
async fn find(pool: &DatabasePool, id: i64) -> Result<Self, sqlx::Error>;
async fn all(pool: &DatabasePool) -> Result<Vec<Self>, sqlx::Error>;
async fn save(&self, pool: &DatabasePool) -> Result<i64, sqlx::Error>;
async fn delete(pool: &DatabasePool, id: i64) -> Result<bool, sqlx::Error>;
fn query(pool: &DatabasePool) -> QueryBuilder<'_, Self> {
QueryBuilder::new(pool, Self::TABLE)
}
async fn has_many<R>(
pool: &DatabasePool,
foreign_key: &str,
local_id: i64,
) -> Result<Vec<R>, sqlx::Error>
where
R: Model,
{
R::query(pool)
.filter(foreign_key, "=", local_id)
.get()
.await
}
async fn has_one<R>(
pool: &DatabasePool,
foreign_key: &str,
local_id: i64,
) -> Result<R, sqlx::Error>
where
R: Model,
{
R::query(pool)
.filter(foreign_key, "=", local_id)
.first()
.await
}
async fn belongs_to<R>(pool: &DatabasePool, foreign_key_id: i64) -> Result<R, sqlx::Error>
where
R: Model,
{
R::find(pool, foreign_key_id).await
}
async fn belongs_to_many<R>(
pool: &DatabasePool,
pivot_table: &str,
foreign_key: &str,
related_key: &str,
local_id: i64,
) -> Result<Vec<R>, sqlx::Error>
where
R: Model,
{
R::query(pool)
.select(&format!("{}.*", R::TABLE))
.join(&format!(
"JOIN {} p ON {}.id = p.{}",
pivot_table,
R::TABLE,
related_key
))
.filter(&format!("p.{}", foreign_key), "=", local_id)
.get()
.await
}
async fn eager_load(
_relation: &str,
_items: &mut [Self],
_pool: &DatabasePool,
) -> Result<(), sqlx::Error> {
Ok(())
}
}