Skip to main content

max / makenotwork

1.1 KB · 43 lines History Blame Raw
1 use super::{CommunityRole, PgPool, Uuid};
2
3 /// Ensure a user has a membership in a community with the given role.
4 /// Creates membership if none exists, does nothing if already a member.
5 #[tracing::instrument(skip_all)]
6 pub async fn ensure_membership_with_role(
7 pool: &PgPool,
8 user_id: Uuid,
9 community_id: Uuid,
10 role: CommunityRole,
11 ) -> Result<(), sqlx::Error> {
12 sqlx::query!(
13 "INSERT INTO memberships (user_id, community_id, role)
14 VALUES ($1, $2, $3)
15 ON CONFLICT (user_id, community_id) DO NOTHING",
16 user_id,
17 community_id,
18 role.as_str(),
19 )
20 .execute(pool)
21 .await?;
22 Ok(())
23 }
24
25 /// Ensure a user has a membership in a community. Creates a 'member' role if none exists.
26 #[tracing::instrument(skip_all)]
27 pub async fn ensure_membership(
28 pool: &PgPool,
29 user_id: Uuid,
30 community_id: Uuid,
31 ) -> Result<(), sqlx::Error> {
32 sqlx::query!(
33 "INSERT INTO memberships (user_id, community_id, role)
34 VALUES ($1, $2, 'member')
35 ON CONFLICT (user_id, community_id) DO NOTHING",
36 user_id,
37 community_id,
38 )
39 .execute(pool)
40 .await?;
41 Ok(())
42 }
43