|
| 1 | +use crate::discord::ise; |
1 | 2 | use crate::guilds::verify::models::Verify; |
2 | 3 | use crate::guilds::votes::models::Vote; |
| 4 | +use http::StatusCode; |
3 | 5 | use lambda_http::tracing::{error}; |
4 | 6 | use serde::{Deserialize, Serialize}; |
5 | 7 | use std::collections::HashMap; |
@@ -82,17 +84,44 @@ impl Guild { |
82 | 84 | } |
83 | 85 | } |
84 | 86 |
|
85 | | - pub async fn save(&self, pg_pool: &Pool<Postgres>) { |
86 | | - match sqlx::query("INSERT INTO guilds (id, verify, vote) VALUES ($1, $2, $3) ON CONFLICT (id) DO UPDATE SET verify = $2, vote = $3, updated_at = CURRENT_TIMESTAMP") |
| 87 | + pub async fn save(&self, pg_pool: &Pool<Postgres>) -> Result<(), StatusCode> { |
| 88 | + sqlx::query("INSERT INTO guilds (id, verify, vote) VALUES ($1, $2, $3) ON CONFLICT (id) DO UPDATE SET verify = $2, vote = $3, updated_at = CURRENT_TIMESTAMP") |
87 | 89 | .bind(BigDecimal::from(self.guild_id.into_nonzero().get())) |
88 | | - .bind(serde_json::to_string(&self.verify).unwrap()) |
89 | | - .bind(serde_json::to_string(&self.vote).unwrap()) |
| 90 | + .bind(serde_json::to_string(&self.verify).map_err(ise)?) |
| 91 | + .bind(serde_json::to_string(&self.vote).map_err(ise)?) |
90 | 92 | .execute(pg_pool) |
91 | | - .await { |
92 | | - Ok(_) => (), |
93 | | - Err(e) => { |
94 | | - error!("Error saving user to DB: {}", e); |
95 | | - } |
96 | | - } |
| 93 | + .await |
| 94 | + .map_err(ise)?; |
| 95 | + Ok(()) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +#[cfg(test)] |
| 100 | +mod tests { |
| 101 | + use super::*; |
| 102 | + |
| 103 | + /// Regression test for issue #21: `Guild::save` must return a `Result` |
| 104 | + /// that surfaces DB errors to the caller instead of swallowing them and |
| 105 | + /// reporting success. We point a lazily-connecting pool at a port that |
| 106 | + /// nothing is listening on, so the first query fails fast with a |
| 107 | + /// connection error, exercising the exact `sqlx::Error` -> `StatusCode` |
| 108 | + /// mapping path used in production. This does not require a live |
| 109 | + /// Postgres server, but a real DB integration test would additionally |
| 110 | + /// be valuable in CI to cover the success path end-to-end. |
| 111 | + #[tokio::test] |
| 112 | + async fn save_propagates_db_errors_instead_of_swallowing_them() { |
| 113 | + let pool = sqlx::postgres::PgPoolOptions::new() |
| 114 | + .connect_lazy("postgres://baduser:badpass@127.0.0.1:1/nonexistent_db") |
| 115 | + .expect("connect_lazy should not eagerly connect"); |
| 116 | + |
| 117 | + let guild = Guild::default(); |
| 118 | + let result = guild.save(&pool).await; |
| 119 | + |
| 120 | + assert_eq!( |
| 121 | + result, |
| 122 | + Err(StatusCode::INTERNAL_SERVER_ERROR), |
| 123 | + "save() must return an Err(StatusCode) when the underlying DB write fails, \ |
| 124 | + not silently succeed" |
| 125 | + ); |
97 | 126 | } |
98 | 127 | } |
0 commit comments