Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 48 additions & 28 deletions crates/crates_io_database/src/models/email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub struct Email {
pub user_id: i32,
pub email: String,
pub verified: bool,
pub primary: bool,
#[diesel(deserialize_as = String, serialize_as = String)]
pub token: SecretString,
}
Expand All @@ -24,46 +25,65 @@ pub struct NewEmail<'a> {
pub email: &'a str,
#[builder(default = false)]
pub verified: bool,
#[builder(default = false)]
pub primary: bool,
}

impl NewEmail<'_> {
pub async fn insert(&self, conn: &mut AsyncPgConnection) -> QueryResult<()> {
pub async fn insert(&self, conn: &mut AsyncPgConnection) -> QueryResult<Email> {
diesel::insert_into(emails::table)
.values(self)
.execute(conn)
.await?;

Ok(())
.returning(Email::as_returning())
.get_result(conn)
.await
}

/// Inserts the email into the database and returns the confirmation token,
/// or does nothing if it already exists and returns `None`.
pub async fn insert_if_missing(
/// Inserts the email into the database and returns it, unless the user already has a
/// primary email, in which case it will do nothing and return `None`.
pub async fn insert_primary_if_missing(
&self,
conn: &mut AsyncPgConnection,
) -> QueryResult<Option<SecretString>> {
diesel::insert_into(emails::table)
.values(self)
.on_conflict_do_nothing()
.returning(emails::token)
.get_result::<String>(conn)
.await
.map(Into::into)
.optional()
) -> QueryResult<Option<Email>> {
// Check if the user already has a primary email
let primary_count = emails::table
.filter(emails::user_id.eq(self.user_id))
.filter(emails::primary.eq(true))
.count()
.get_result::<i64>(conn)
.await?;

if primary_count > 0 {
return Ok(None); // User already has a primary email
}

self.insert(conn).await.map(Some)
}

pub async fn insert_or_update(
// Inserts an email for the user, replacing the primary email if it exists.
pub async fn insert_or_update_primary(
&self,
conn: &mut AsyncPgConnection,
) -> QueryResult<SecretString> {
diesel::insert_into(emails::table)
.values(self)
.on_conflict(emails::user_id)
.do_update()
.set(self)
.returning(emails::token)
.get_result::<String>(conn)
.await
.map(Into::into)
) -> QueryResult<Email> {
// Attempt to update an existing primary email
let updated_email = diesel::update(
emails::table
.filter(emails::user_id.eq(self.user_id))
.filter(emails::primary.eq(true)),
)
.set((
emails::email.eq(self.email),
emails::verified.eq(self.verified),
))
.returning(Email::as_returning())
.get_result(conn)
.await
.optional()?;

if let Some(email) = updated_email {
Ok(email)
} else {
// Otherwise, insert a new email
self.insert(conn).await
}
}
}
6 changes: 4 additions & 2 deletions crates/crates_io_database/src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,17 @@ impl User {
Ok(users.collect())
}

/// Queries the database for the verified emails
/// belonging to a given user
/// Queries the database for a verified email address belonging to the user.
/// It will ideally return the primary email address if it exists and is
/// verified, otherwise, it will return any verified email address.
pub async fn verified_email(
&self,
conn: &mut AsyncPgConnection,
) -> QueryResult<Option<String>> {
Email::belonging_to(self)
.select(emails::email)
.filter(emails::verified.eq(true))
.order(emails::primary.desc())
.first(conn)
.await
.optional()
Expand Down
16 changes: 16 additions & 0 deletions crates/crates_io_database/src/schema.patch
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@
/// The `target` column of the `dependencies` table.
///
/// Its SQL type is `Nullable<Varchar>`.
@@ -536,13 +536,14 @@
///
/// Its SQL type is `Nullable<Timestamptz>`.
///
/// (Automatically generated by Diesel.)
token_generated_at -> Nullable<Timestamptz>,
/// Whether this email is the primary email address for the user.
- is_primary -> Bool,
+ #[sql_name = "is_primary"]
+ primary -> Bool,
}
}

diesel::table! {
/// Representation of the `follows` table.
///
@@ -710,6 +702,24 @@
}

Expand Down
3 changes: 3 additions & 0 deletions crates/crates_io_database/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,9 @@ diesel::table! {
///
/// (Automatically generated by Diesel.)
token_generated_at -> Nullable<Timestamptz>,
/// Whether this email is the primary email address for the user.
#[sql_name = "is_primary"]
primary -> Bool,
}
}

Expand Down
Loading