use async_trait::async_trait;
use serde::{Serialize, Deserialize};
use sqlx::FromRow;
use crate::database::{connection::DatabasePool, model::Model};
#[derive(Debug, Serialize, Deserialize, FromRow, Clone, Default)]
pub struct {{name}} {
pub id: i64,
{{fields}}
pub created_at: Option<String>,
pub updated_at: Option<String>,
pub deleted_at: Option<String>,
}
impl {{name}} {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl Model for {{name}} {
const TABLE: &'static str = "{{table_name}}";
async fn find(pool: &DatabasePool, id: i64) -> Result<Self, sqlx::Error> {
Self::query(pool).where_eq("id", id).first().await
}
async fn all(pool: &DatabasePool) -> Result<Vec<Self>, sqlx::Error> {
Self::query(pool).get().await
}
async fn save(&self, pool: &DatabasePool) -> Result<i64, sqlx::Error> {
if self.id > 0 {
sqlx::query("UPDATE {{table_name}} SET {{sql_update}} WHERE id = ?")
{{bind_fields}}
.bind(self.id)
.execute(&pool.pool)
.await?;
Ok(self.id)
} else {
let result = sqlx::query(
"INSERT INTO {{table_name}} ({{sql_fields}}) VALUES ({{sql_placeholders}})"
)
{{bind_fields}}
.execute(&pool.pool)
.await?;
Ok(result.last_insert_id().unwrap_or(0))
}
}
async fn delete(pool: &DatabasePool, id: i64) -> Result<bool, sqlx::Error> {
sqlx::query("UPDATE {{table_name}} SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?")
.bind(id)
.execute(&pool.pool)
.await?;
Ok(true)
}
}