use rusqlite::{params, OptionalExtension}; use crate::db::{Db, Writer}; use crate::error::Result; use crate::time; // ----------------------------------------------------------------- notice -- pub fn put_notice_once( writer: &Writer, pkgbase_id: i64, kind: &str, severity: &str, detail: &serde_json::Value, ) -> Result> { let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); let at = time::now(); writer.tx(move |tx| { let exists: Option = tx .query_row( "SELECT id FROM notice WHERE pkgbase_id=?1 AND kind=?2 AND detail_json=?3 AND acknowledged_at IS NULL ORDER BY id DESC LIMIT 1", params![pkgbase_id, k, d], |r| r.get(0), ) .optional()?; if exists.is_some() { return Ok(None); } tx.execute( "INSERT INTO notice (pkgbase_id, kind, severity, detail_json, created_at) VALUES (?1,?2,?3,?4,?5)", params![pkgbase_id, k, s, d, at], )?; Ok(Some(tx.last_insert_rowid())) }) } #[derive(Debug, Clone)] pub struct NoticeRow { pub id: i64, pub pkgbase: String, pub kind: String, pub severity: String, pub detail_json: String, pub created_at: String, pub acknowledged_at: Option, } pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result> { db.read(|c| { let sql = format!( "SELECT n.id, b.name, n.kind, n.severity, n.detail_json, n.created_at, n.acknowledged_at FROM notice n JOIN pkgbase b ON b.id = n.pkgbase_id {} ORDER BY (n.severity='high') DESC, n.created_at DESC LIMIT 500", if include_acknowledged { "" } else { "WHERE n.acknowledged_at IS NULL" } ); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map([], |r| { Ok(NoticeRow { id: r.get(0)?, pkgbase: r.get(1)?, kind: r.get(2)?, severity: r.get(3)?, detail_json: r.get(4)?, created_at: r.get(5)?, acknowledged_at: r.get(6)?, }) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn acknowledge_notice(writer: &Writer, id: i64) -> Result<()> { let at = time::now(); writer.tx(move |tx| { tx.execute("UPDATE notice SET acknowledged_at=?1 WHERE id=?2", params![at, id])?; Ok(()) }) }