use anyhow::anyhow; use sqlx::postgres::PgRow; use sqlx::Row; use cove_net_common::id::SnowflakeID; use crate::part::BindQuery; use crate::part::insert::SqlInsert; use crate::part::select::SqlSelect; use crate::part::sql_where::SqlWhere; use crate::rows::{InsertableRow, SelectableRow, TableRow, WhereRow}; pub struct AttachmentRow { pub id: SnowflakeID, pub uploader_id: SnowflakeID, pub channel_id: Option, pub file_size: i32, pub cdn_url: String } impl TableRow for AttachmentRow { type Error = anyhow::Error; fn get_table_name() -> &'static str { "attachments" } } impl InsertableRow for AttachmentRow { fn insert(&'_ self) -> SqlInsert { SqlInsert::with_table(Self::get_table_name()) .col::("id") .col::("uploader_id") .opt_col::("channel_id") .col::("file_size") .col::("cdn_url") } fn bind<'a>(&'a self, query: BindQuery<'a>) -> Result, Self::Error> { query.bind(&self.id)? .bind(&self.uploader_id)? .bind(&self.channel_id)? .bind(&self.file_size)? .bind(&self.cdn_url) } } impl SelectableRow for AttachmentRow {} impl WhereRow for AttachmentRow { fn bind<'a>(&'a self, wheres: SqlWhere, query: BindQuery<'a>) -> Result, Self::Error> { let mut query = query; for (_, col) in wheres.indexed_placeholders { query = match col.as_str() { "id" => query.bind(&self.id)?, "uploader_id" => query.bind(&self.uploader_id)?, "channel_id" => query.bind(&self.channel_id)?, "file_size" => query.bind(&self.file_size)?, "cdn_url" => query.bind(&self.cdn_url)?, _ => return Err(anyhow!("No column {col} exists for table attachments")) } } Ok(query) } } impl TryFrom for AttachmentRow { type Error = anyhow::Error; fn try_from(value: PgRow) -> Result { Ok(Self { id: value.try_get("id")?, uploader_id: value.try_get("uploader_id")?, channel_id: value.try_get("channel_id")?, file_size: value.try_get("file_size")?, cdn_url: value.try_get("cdn_url")?, }) } }