Skip to main content

max / makenotwork

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