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)
}
fn where_eq<'a, V>(pool: &'a DatabasePool, column: &'a str, value: V) -> QueryBuilder<'a, Self>
where
V: 'a + Send + sqlx::Encode<'a, sqlx::Any> + sqlx::Type<sqlx::Any>,
{
Self::query(pool).where_eq(column, value)
}
fn where_like<'a, V>(pool: &'a DatabasePool, column: &'a str, pattern: V) -> QueryBuilder<'a, Self>
where
V: 'a + Send + sqlx::Encode<'a, sqlx::Any> + sqlx::Type<sqlx::Any>,
{
Self::query(pool).where_like(column, pattern)
}
fn where_null<'a>(pool: &'a DatabasePool, column: &'a str) -> QueryBuilder<'a, Self> {
Self::query(pool).where_null(column)
}
fn where_not_null<'a>(pool: &'a DatabasePool, column: &'a str) -> QueryBuilder<'a, Self> {
Self::query(pool).where_not_null(column)
}
fn latest<'a>(pool: &'a DatabasePool) -> QueryBuilder<'a, Self> {
Self::query(pool).latest()
}
fn oldest<'a>(pool: &'a DatabasePool) -> QueryBuilder<'a, Self> {
Self::query(pool).oldest()
}
async fn count(pool: &DatabasePool) -> Result<i64, sqlx::Error> {
Self::query(pool).count().await
}
async fn paginate(
pool: &DatabasePool,
page: usize,
per_page: usize,
) -> Result<super::orm::LengthAwarePaginator<Self>, sqlx::Error> {
Self::query(pool).paginate(page, per_page).await
}
async fn destroy(pool: &DatabasePool, id: i64) -> Result<bool, sqlx::Error> {
Self::delete(pool, id).await
}
async fn exists(pool: &DatabasePool) -> Result<bool, sqlx::Error> {
Self::query(pool).exists().await
}
async fn find_or_fail(pool: &DatabasePool, id: i64) -> Result<Self, sqlx::Error> {
Self::find(pool, id).await
}
async fn first_or_create<K, V>(
pool: &DatabasePool,
attributes: impl IntoIterator<Item = (K, V)> + Send,
values: impl IntoIterator<Item = (K, V)> + Send,
) -> Result<Self, sqlx::Error>
where
K: AsRef<str>,
V: ToString,
{
let attr_vec: Vec<(String, String)> = attributes
.into_iter()
.map(|(k, v)| (k.as_ref().to_string(), v.to_string()))
.collect();
let val_vec: Vec<(String, String)> = values
.into_iter()
.map(|(k, v)| (k.as_ref().to_string(), v.to_string()))
.collect();
let mut builder = Self::query(pool);
for (k, v) in &attr_vec {
builder = builder.where_eq_str(k, v);
}
if let Some(item) = builder.first().await? {
return Ok(item);
}
let mut create_map: Vec<(String, String)> = attr_vec;
for (key, val) in val_vec {
if !create_map.iter().any(|(existing_k, _)| existing_k == &key) {
create_map.push((key, val));
}
}
Self::create(pool, create_map).await
}
async fn create<K, V>(
pool: &DatabasePool,
data: impl IntoIterator<Item = (K, V)> + Send,
) -> Result<Self, sqlx::Error>
where
K: AsRef<str>,
V: ToString,
{
let pairs: Vec<(String, String)> = data
.into_iter()
.map(|(k, v)| (k.as_ref().to_string(), v.to_string()))
.collect();
if pairs.is_empty() {
return Err(sqlx::Error::Decode("No fields provided for create".into()));
}
let keys: Vec<String> = pairs.iter().map(|p| p.0.clone()).collect();
let placeholders = vec!["?"; keys.len()].join(", ");
let sql = format!(
"INSERT INTO {} ({}) VALUES ({})",
Self::TABLE,
keys.join(", "),
placeholders
);
let mut query = sqlx::query(&sql);
for pair in &pairs {
query = query.bind(&pair.1);
}
let res = query.execute(&pool.pool).await?;
let inserted_id = res.last_insert_id().unwrap_or(0);
if inserted_id != 0 {
if let Ok(item) = Self::find(pool, inserted_id as i64).await {
return Ok(item);
}
}
let last_item = Self::query(pool).order_by("id", "DESC").first_or_fail().await?;
Ok(last_item)
}
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_or_fail()
.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(())
}
}