54 lines
1.4 KiB
Rust
54 lines
1.4 KiB
Rust
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<String>,
|
|
pub expiration: Option<i64>,
|
|
pub max_views: Option<i64>,
|
|
pub views: i64,
|
|
pub created_at: i64,
|
|
pub updated_at: Option<i64>,
|
|
pub owner: Option<String>,
|
|
}
|
|
|
|
#[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<Option<Self>, 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)
|
|
}
|
|
}
|