use sqlx::SqlitePool; #[derive(serde::Serialize, sqlx::FromRow)] pub struct Paste { pub id: String, #[sqlx(rename = "type")] pub paste_type: PasteType, pub content: String, pub language: Option, pub expiration: Option, pub max_views: Option, pub views: i64, pub created_at: i64, pub updated_at: Option, pub owner: Option, } #[derive(serde::Serialize, sqlx::Type)] #[repr(i64)] pub enum PasteType { TextV1 = 0, UrlV1 = 100, } impl Paste { pub async fn read( db: &SqlitePool, id: &str, paste_type: PasteType, ) -> Result, sqlx::Error> { let mut transaction = db.begin().await?; let paste = sqlx::query_as::<_, Self>( "UPDATE notes SET views = views + 1 WHERE type = ? AND id = ? AND (expiration IS NULL OR expiration > unixepoch()) AND (max_views IS NULL OR views < max_views) RETURNING *", ) .bind(paste_type) .bind(id) .fetch_optional(&mut *transaction) .await?; if let Some(paste) = &paste && paste.max_views.is_some_and(|max| paste.views >= max) { sqlx::query("DELETE FROM notes WHERE id = ?") .bind(&paste.id) .execute(&mut *transaction) .await?; } transaction.commit().await?; Ok(paste) } }