refactor model db methods

This commit is contained in:
Brent Schroeter 2025-03-12 23:16:22 -07:00
parent 4c61bd6786
commit bbb5550caf
6 changed files with 139 additions and 75 deletions

View file

@ -42,14 +42,19 @@ impl Channel {
} }
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn with_id(channel_id: Uuid) -> _ { pub fn with_id<'a>(channel_id: &'a Uuid) -> _ {
channels::id.eq(channel_id) channels::id.eq(channel_id)
} }
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn with_team(team_id: Uuid) -> _ { pub fn with_team<'a>(team_id: &'a Uuid) -> _ {
channels::team_id.eq(team_id) channels::team_id.eq(team_id)
} }
#[auto_type(no_type_alias)]
pub fn where_enabled_by_default() -> _ {
channels::enable_by_default.eq(true)
}
} }
/** /**

View file

@ -3,7 +3,7 @@
use anyhow::Result; use anyhow::Result;
use chrono::{DateTime, TimeDelta, Utc}; use chrono::{DateTime, TimeDelta, Utc};
use diesel::{ use diesel::{
dsl::{auto_type, AsSelect}, dsl::{auto_type, insert_into, AsSelect},
pg::Pg, pg::Pg,
prelude::*, prelude::*,
sql_types::Timestamptz, sql_types::Timestamptz,
@ -28,6 +28,25 @@ pub struct Governor {
} }
impl Governor { impl Governor {
pub fn insert_new<'a>(
db_conn: &mut diesel::PgConnection,
team_id: &'a Uuid,
project_id: Option<&'a Uuid>,
window_size: &'a TimeDelta,
max_count: i32,
) -> Result<Self> {
let id: Uuid = Uuid::now_v7();
Ok(insert_into(governors::table)
.values((
governors::team_id.eq(team_id),
governors::id.eq(id),
governors::project_id.eq(project_id),
governors::window_size.eq(window_size),
governors::max_count.eq(max_count),
))
.get_result(db_conn)?)
}
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn all() -> _ { pub fn all() -> _ {
let select: AsSelect<Governor, Pg> = Governor::as_select(); let select: AsSelect<Governor, Pg> = Governor::as_select();

View file

@ -1,5 +1,6 @@
use anyhow::Result;
use diesel::{ use diesel::{
dsl::{auto_type, AsSelect, Eq}, dsl::{auto_type, insert_into, AsSelect, Eq},
pg::Pg, pg::Pg,
prelude::*, prelude::*,
}; };
@ -21,6 +22,34 @@ pub struct Project {
} }
impl Project { impl Project {
pub fn insert_new<'a>(
db_conn: &mut diesel::PgConnection,
team_id: &'a Uuid,
name: &'a str,
) -> Result<Self> {
let default_channels = Channel::all()
.filter(Channel::with_team(team_id))
.filter(Channel::where_enabled_by_default())
.load(db_conn)?;
let id: Uuid = Uuid::now_v7();
let project: Self = insert_into(projects::table)
.values((
projects::id.eq(id),
projects::team_id.eq(team_id),
projects::name.eq(name),
))
.get_result(db_conn)?;
for channel in default_channels {
insert_into(channel_selections::table)
.values((
channel_selections::project_id.eq(&project.id),
channel_selections::channel_id.eq(&channel.id),
))
.execute(db_conn)?;
}
Ok(project)
}
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn all() -> _ { pub fn all() -> _ {
let select: AsSelect<Project, Pg> = Project::as_select(); let select: AsSelect<Project, Pg> = Project::as_select();

View file

@ -27,7 +27,6 @@ use crate::{
email::{MailSender as _, Mailer}, email::{MailSender as _, Mailer},
guards, guards,
nav_state::{Breadcrumb, NavState}, nav_state::{Breadcrumb, NavState},
projects::Project,
schema::{self, channel_selections, channels}, schema::{self, channel_selections, channels},
settings::Settings, settings::Settings,
team_memberships::TeamMembership, team_memberships::TeamMembership,
@ -213,15 +212,15 @@ async fn post_new_team(
user_id: current_user.id, user_id: current_user.id,
}; };
db_conn db_conn
.interact(move |conn| { .interact::<_, Result<(), AppError>>(move |conn| {
conn.transaction(move |conn| { conn.transaction::<(), AppError, _>(move |conn| {
insert_into(schema::teams::table) insert_into(schema::teams::table)
.values(team) .values(&team)
.execute(conn)?; .execute(conn)?;
insert_into(schema::team_memberships::table) insert_into(schema::team_memberships::table)
.values(team_membership) .values(&team_membership)
.execute(conn)?; .execute(conn)?;
diesel::QueryResult::Ok(()) Ok(())
}) })
}) })
.await .await
@ -286,12 +285,18 @@ async fn channels_page(
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?; let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?;
let team_filter = Channel::with_team(team_id); let channels = {
let channels = db_conn let team_id = team_id.clone();
.interact(move |conn| Channel::all().filter(team_filter).load(conn)) db_conn
.await .interact(move |conn| {
.unwrap() Channel::all()
.context("Failed to load channels list.")?; .filter(Channel::with_team(&team_id))
.load(conn)
})
.await
.unwrap()
.context("Failed to load channels list.")?
};
let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?; let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?;
let nav_state = NavState::new() let nav_state = NavState::new()
@ -379,25 +384,27 @@ async fn channel_page(
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?; let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?;
let id_filter = Channel::with_id(channel_id); let channel = {
let team_filter = Channel::with_team(team_id.clone()); let channel_id = channel_id.clone();
let channel = match db_conn let team_id = team_id.clone();
.interact(move |conn| { match db_conn
Channel::all() .interact(move |conn| {
.filter(id_filter) Channel::all()
.filter(team_filter) .filter(Channel::with_id(&channel_id))
.first(conn) .filter(Channel::with_team(&team_id))
.optional() .first(conn)
}) .optional()
.await })
.unwrap()? .await
{ .unwrap()?
None => { {
return Err(AppError::NotFoundError( None => {
"Channel with that team and ID not found".to_string(), return Err(AppError::NotFoundError(
)); "Channel with that team and ID not found".to_string(),
));
}
Some(channel) => channel,
} }
Some(channel) => channel,
}; };
let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?; let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?;
@ -457,21 +464,27 @@ async fn update_channel(
guards::require_valid_csrf_token(&form_body.csrf_token, &current_user, &db_conn).await?; guards::require_valid_csrf_token(&form_body.csrf_token, &current_user, &db_conn).await?;
guards::require_team_membership(&current_user, &team_id, &db_conn).await?; guards::require_team_membership(&current_user, &team_id, &db_conn).await?;
let id_filter = Channel::with_id(channel_id.clone()); let updated_rows = {
let team_filter = Channel::with_team(team_id.clone()); let channel_id = channel_id.clone();
let updated_rows = db_conn let team_id = team_id.clone();
.interact(move |conn| { db_conn
update(channels::table.filter(id_filter).filter(team_filter)) .interact(move |conn| {
update(
channels::table
.filter(Channel::with_id(&channel_id))
.filter(Channel::with_team(&team_id)),
)
.set(( .set((
channels::name.eq(form_body.name), channels::name.eq(form_body.name),
channels::enable_by_default channels::enable_by_default
.eq(form_body.enable_by_default.unwrap_or("false".to_string()) == "true"), .eq(form_body.enable_by_default.unwrap_or("false".to_string()) == "true"),
)) ))
.execute(conn) .execute(conn)
}) })
.await .await
.unwrap() .unwrap()
.context("Failed to load Channel while updating.")?; .context("Failed to load Channel while updating.")?
};
if updated_rows != 1 { if updated_rows != 1 {
return Err(AppError::NotFoundError( return Err(AppError::NotFoundError(
"Channel with that team and ID not found".to_string(), "Channel with that team and ID not found".to_string(),
@ -490,10 +503,10 @@ async fn update_channel(
* Helper function to query a channel from the database by ID and team, and * Helper function to query a channel from the database by ID and team, and
* return an appropriate error if no such channel exists. * return an appropriate error if no such channel exists.
*/ */
fn get_channel_by_params( fn get_channel_by_params<'a>(
conn: &mut PgConnection, conn: &mut PgConnection,
team_id: Uuid, team_id: &'a Uuid,
channel_id: Uuid, channel_id: &'a Uuid,
) -> Result<Channel, AppError> { ) -> Result<Channel, AppError> {
match Channel::all() match Channel::all()
.filter(Channel::with_id(channel_id)) .filter(Channel::with_id(channel_id))
@ -551,14 +564,14 @@ async fn update_channel_email_recipient(
.interact(move |conn| { .interact(move |conn| {
// TODO: transaction retries // TODO: transaction retries
conn.transaction::<_, AppError, _>(move |conn| { conn.transaction::<_, AppError, _>(move |conn| {
let channel = get_channel_by_params(conn, team_id, channel_id)?; let channel = get_channel_by_params(conn, &team_id, &channel_id)?;
let new_config = BackendConfig::Email(EmailBackendConfig { let new_config = BackendConfig::Email(EmailBackendConfig {
recipient, recipient,
verification_code, verification_code,
verification_code_guesses: 0, verification_code_guesses: 0,
..channel.backend_config.try_into()? ..channel.backend_config.try_into()?
}); });
let num_rows = update(channels::table.filter(Channel::with_id(channel.id))) let num_rows = update(channels::table.filter(Channel::with_id(&channel.id)))
.set(channels::backend_config.eq(new_config)) .set(channels::backend_config.eq(new_config))
.execute(conn)?; .execute(conn)?;
if num_rows != 1 { if num_rows != 1 {
@ -641,7 +654,7 @@ async fn verify_email(
db_conn db_conn
.interact(move |conn| { .interact(move |conn| {
conn.transaction::<(), AppError, _>(move |conn| { conn.transaction::<(), AppError, _>(move |conn| {
let channel = get_channel_by_params(conn, team_id, channel_id)?; let channel = get_channel_by_params(conn, &team_id, &channel_id)?;
let config: EmailBackendConfig = channel.backend_config.try_into()?; let config: EmailBackendConfig = channel.backend_config.try_into()?;
if config.verified { if config.verified {
return Err(AppError::BadRequestError( return Err(AppError::BadRequestError(
@ -666,7 +679,7 @@ async fn verify_email(
..config ..config
} }
}; };
update(channels::table.filter(Channel::with_id(channel_id))) update(channels::table.filter(Channel::with_id(&channel_id)))
.set(channels::backend_config.eq(Into::<BackendConfig>::into(new_config))) .set(channels::backend_config.eq(Into::<BackendConfig>::into(new_config)))
.execute(conn)?; .execute(conn)?;
Ok(()) Ok(())
@ -722,12 +735,18 @@ async fn project_page(
.map(|channel| channel.id) .map(|channel| channel.id)
.collect(); .collect();
let team_filter = Channel::with_team(team.id.clone()); let team_channels = {
let team_channels = db_conn let team_id = team.id.clone();
.interact(move |conn| Channel::all().filter(team_filter).load(conn)) db_conn
.await .interact(move |conn| {
.unwrap() Channel::all()
.context("failed to load team channels")?; .filter(Channel::with_team(&team_id))
.load(conn)
})
.await
.unwrap()
.context("failed to load team channels")?
};
let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id)).await?; let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id)).await?;
let nav_state = NavState::new() let nav_state = NavState::new()

View file

@ -1,6 +1,6 @@
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use axum::extract::FromRef; use axum::extract::FromRef;
use config::{Config, ConfigError, Environment}; use config::{Config, Environment};
use dotenvy::dotenv; use dotenvy::dotenv;
use serde::Deserialize; use serde::Deserialize;

View file

@ -21,7 +21,7 @@ use crate::{
channels::Channel, channels::Channel,
governors::Governor, governors::Governor,
projects::Project, projects::Project,
schema::{api_keys, governors, messages, projects}, schema::{api_keys, messages},
}; };
const TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC: i64 = 300; const TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC: i64 = 300;
@ -90,13 +90,7 @@ async fn say_get(
.context("failed to load project")? .context("failed to load project")?
{ {
Some(project) => project, Some(project) => project,
None => insert_into(projects::table) None => Project::insert_new(conn, &api_key.team_id, &project_name)
.values((
projects::id.eq(Uuid::now_v7()),
projects::team_id.eq(api_key.team_id),
projects::name.eq(project_name),
))
.get_result(conn)
.context("failed to insert project")?, .context("failed to insert project")?,
}, },
) )
@ -120,16 +114,14 @@ async fn say_get(
diesel::QueryResult::Ok(governor) => Ok(governor), diesel::QueryResult::Ok(governor) => Ok(governor),
diesel::QueryResult::Err(diesel::result::Error::NotFound) => { diesel::QueryResult::Err(diesel::result::Error::NotFound) => {
// Lazily initialize governor // Lazily initialize governor
Ok(diesel::insert_into(governors::table) Governor::insert_new(
.values(( conn,
governors::team_id.eq(team_id), &team_id,
governors::id.eq(Uuid::now_v7()), None,
governors::project_id.eq(None as Option<Uuid>), &TimeDelta::seconds(TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC),
governors::window_size TEAM_GOVERNOR_DEFAULT_MAX_COUNT,
.eq(TimeDelta::seconds(TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC)), )
governors::max_count.eq(TEAM_GOVERNOR_DEFAULT_MAX_COUNT), .map_err(Into::into)
))
.get_result(conn)?)
} }
diesel::QueryResult::Err(err) => Err(err.into()), diesel::QueryResult::Err(err) => Err(err.into()),
} }