Lines of
src/sql.rs
from check-in c6d3e97290
that are changed by the sequence of edits moving toward
check-in 44575a91d3:
1: use std::{
2: borrow::Cow,
3: fmt,
4: };
5:
c6d3e97290 2025-07-01 6: use anyhow::{
c6d3e97290 2025-07-01 7: Result,
c6d3e97290 2025-07-01 8: bail,
c6d3e97290 2025-07-01 9: };
10: use async_std::sync::{
11: Arc,
12: Mutex,
13: };
14: use chrono::{
15: DateTime,
16: FixedOffset,
17: Local,
18: };
19: use sqlx::{
20: Postgres,
21: Row,
22: postgres::PgPoolOptions,
23: pool::PoolConnection,
24: };
25:
26: #[derive(sqlx::FromRow, Debug)]
27: pub struct List {
28: pub source_id: i32,
29: pub channel: String,
30: pub enabled: bool,
31: pub url: String,
32: pub iv_hash: Option<String>,
33: pub url_re: Option<String>,
34: }
35:
36: impl fmt::Display for List {
c6d3e97290 2025-07-01 37: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
38: write!(f, "#{} \\*ļøā£ `{}` {}\nš `{}`", self.source_id, self.channel,
39: match self.enabled {
40: true => "š enabled",
41: false => "ā disabled",
42: }, self.url)?;
43: if let Some(iv_hash) = &self.iv_hash {
44: write!(f, "\nIV: `{iv_hash}`")?;
45: }
46: if let Some(url_re) = &self.url_re {
47: write!(f, "\nRE: `{url_re}`")?;
48: }
49: Ok(())
50: }
51: }
52:
53: #[derive(sqlx::FromRow, Debug)]
54: pub struct Source {
55: pub channel_id: i64,
56: pub url: String,
57: pub iv_hash: Option<String>,
58: pub owner: i64,
59: pub url_re: Option<String>,
60: }
61:
62: #[derive(sqlx::FromRow)]
63: pub struct Queue {
64: pub source_id: Option<i32>,
65: pub next_fetch: Option<DateTime<Local>>,
66: pub owner: Option<i64>,
67: }
68:
69: #[derive(Clone)]
70: pub struct Db (
71: Arc<Mutex<sqlx::Pool<sqlx::Postgres>>>,
72: );
73:
74: impl Db {
75: pub fn new (pguri: &str) -> Result<Db> {
76: Ok(Db (
77: Arc::new(Mutex::new(PgPoolOptions::new()
78: .max_connections(5)
79: .acquire_timeout(std::time::Duration::new(300, 0))
80: .idle_timeout(std::time::Duration::new(60, 0))
c6d3e97290 2025-07-01 81: .connect_lazy(pguri)?)),
82: ))
83: }
84:
85: pub async fn begin(&self) -> Result<Conn> {
86: let pool = self.0.lock_arc().await;
c6d3e97290 2025-07-01 87: let conn = Conn ( pool.acquire().await? );
88: Ok(conn)
89: }
90: }
91:
92: pub struct Conn (
93: PoolConnection<Postgres>,
94: );
95:
96: impl Conn {
97: pub async fn add_post (&mut self, source_id: i32, date: &DateTime<FixedOffset>, post_url: &str) -> Result<()> {
98: sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);")
99: .bind(source_id)
100: .bind(date)
101: .bind(post_url)
c6d3e97290 2025-07-01 102: .execute(&mut *self.0).await?;
103: Ok(())
104: }
105:
106: pub async fn clean <I> (&mut self, source_id: i32, owner: I) -> Result<Cow<'_, str>>
107: where I: Into<i64> {
108: match sqlx::query("delete from rsstg_post p using rsstg_source s where p.source_id = $1 and owner = $2 and p.source_id = s.source_id;")
109: .bind(source_id)
110: .bind(owner.into())
c6d3e97290 2025-07-01 111: .execute(&mut *self.0).await?.rows_affected() {
112: 0 => { Ok("No data found found.".into()) },
113: x => { Ok(format!("{x} posts purged.").into()) },
114: }
115: }
116:
117: pub async fn delete <I> (&mut self, source_id: i32, owner: I) -> Result<Cow<'_, str>>
118: where I: Into<i64> {
119: match sqlx::query("delete from rsstg_source where source_id = $1 and owner = $2;")
120: .bind(source_id)
121: .bind(owner.into())
c6d3e97290 2025-07-01 122: .execute(&mut *self.0).await?.rows_affected() {
123: 0 => { Ok("No data found found.".into()) },
c6d3e97290 2025-07-01 124: x => { Ok(format!("{} sources removed.", x).into()) },
125: }
126: }
127:
128: pub async fn disable <I> (&mut self, source_id: i32, owner: I) -> Result<&str>
129: where I: Into<i64> {
130: match sqlx::query("update rsstg_source set enabled = false where source_id = $1 and owner = $2")
131: .bind(source_id)
132: .bind(owner.into())
c6d3e97290 2025-07-01 133: .execute(&mut *self.0).await?.rows_affected() {
134: 1 => { Ok("Source disabled.") },
135: 0 => { Ok("Source not found.") },
136: _ => { bail!("Database error.") },
137: }
138: }
139:
140: pub async fn enable <I> (&mut self, source_id: i32, owner: I) -> Result<&str>
141: where I: Into<i64> {
142: match sqlx::query("update rsstg_source set enabled = true where source_id = $1 and owner = $2")
143: .bind(source_id)
144: .bind(owner.into())
c6d3e97290 2025-07-01 145: .execute(&mut *self.0).await?.rows_affected() {
146: 1 => { Ok("Source enabled.") },
147: 0 => { Ok("Source not found.") },
148: _ => { bail!("Database error.") },
149: }
150: }
151:
152: pub async fn exists <I> (&mut self, post_url: &str, id: I) -> Result<Option<bool>>
153: where I: Into<i64> {
154: let row = sqlx::query("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;")
155: .bind(post_url)
156: .bind(id.into())
c6d3e97290 2025-07-01 157: .fetch_one(&mut *self.0).await?;
c6d3e97290 2025-07-01 158: let exists: Option<bool> = row.try_get("exists")?;
159: Ok(exists)
160: }
161:
162: pub async fn get_queue (&mut self) -> Result<Vec<Queue>> {
163: let block: Vec<Queue> = sqlx::query_as("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source where next_fetch < now() + interval '1 minute';")
c6d3e97290 2025-07-01 164: .fetch_all(&mut *self.0).await?;
165: Ok(block)
166: }
167:
168: pub async fn get_list <I> (&mut self, owner: I) -> Result<Vec<List>>
169: where I: Into<i64> {
170: let source: Vec<List> = sqlx::query_as("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id")
171: .bind(owner.into())
c6d3e97290 2025-07-01 172: .fetch_all(&mut *self.0).await?;
173: Ok(source)
174: }
175:
176: pub async fn get_one <I> (&mut self, owner: I, id: i32) -> Result<Option<List>>
177: where I: Into<i64> {
178: let source: Option<List> = sqlx::query_as("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 and source_id = $2")
179: .bind(owner.into())
180: .bind(id)
c6d3e97290 2025-07-01 181: .fetch_optional(&mut *self.0).await?;
182: Ok(source)
183: }
184:
185: pub async fn get_source <I> (&mut self, id: i32, owner: I) -> Result<Source>
186: where I: Into<i64> {
187: let source: Source = sqlx::query_as("select channel_id, url, iv_hash, owner, url_re from rsstg_source where source_id = $1 and owner = $2")
188: .bind(id)
189: .bind(owner.into())
c6d3e97290 2025-07-01 190: .fetch_one(&mut *self.0).await?;
191: Ok(source)
192: }
193:
194: pub async fn set_scrape <I> (&mut self, id: I) -> Result<()>
195: where I: Into<i64> {
196: sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
197: .bind(id.into())
c6d3e97290 2025-07-01 198: .execute(&mut *self.0).await?;
199: Ok(())
200: }
201:
202: pub async fn update <I> (&mut self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: I) -> Result<&str>
203: where I: Into<i64> {
204: match match update {
205: Some(id) => {
206: sqlx::query("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $5, channel = $6, url_re = $7 where source_id = $1")
207: .bind(id)
208: },
209: None => {
210: sqlx::query("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)")
211: },
212: }
213: .bind(channel_id)
214: .bind(url)
215: .bind(iv_hash)
216: .bind(owner.into())
217: .bind(channel)
218: .bind(url_re)
219: .execute(&mut *self.0).await
220: {
221: Ok(_) => Ok(match update {
222: Some(_) => "Channel updated.",
223: None => "Channel added.",
224: }),
225: Err(sqlx::Error::Database(err)) => {
226: match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
227: Some("_bt_check_unique", ) => {
228: Ok("Duplicate key.")
229: },
230: Some(_) => {
231: Ok("Database error.")
232: },
233: None => {
234: Ok("No database error extracted.")
235: },
236: }
237: },
238: Err(err) => {
239: bail!("Sorry, unknown error:\n{err:#?}\n");
240: },
241: }
242: }
243: }