use infra::core::AppState;
use neon_rs::sql::mysql;
use sea_query::{Expr, ExprTrait, Query};
use sqlx::{FromRow, mysql::MySqlRow};

use crate::schema::table::Demo;

pub async fn get_by_id<T>(ctx: &AppState, id: i64, cols: Option<Vec<Demo>>) -> anyhow::Result<Option<T>>
where
    T: for<'r> FromRow<'r, MySqlRow> + Send + Unpin,
{
    let mut query = Query::select();

    let stmt = query.from(Demo::Table).and_where(Expr::col(Demo::Id).eq(id));

    if let Some(v) = cols {
        stmt.columns(v);
    } else {
        stmt.expr(Expr::cust("*"));
    }

    mysql::find_one(ctx.db(), stmt.to_owned()).await
}
