Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
82 changes: 54 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 is_primary: bool,
#[diesel(deserialize_as = String, serialize_as = String)]
pub token: SecretString,
}
Expand All @@ -24,46 +25,71 @@ pub struct NewEmail<'a> {
pub email: &'a str,
#[builder(default = false)]
pub verified: bool,
#[builder(default = false)]
pub is_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::is_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> {
if self.is_primary {
return Err(diesel::result::Error::QueryBuilderError(
"Cannot use insert_or_update_primary with a non-primary email".into(),
));
}

// Attempt to update an existing primary email
let updated_email = diesel::update(
emails::table
.filter(emails::user_id.eq(self.user_id))
.filter(emails::is_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 @@ -59,15 +59,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::is_primary.desc())
.first(conn)
.await
.optional()
Expand Down
4 changes: 2 additions & 2 deletions crates/crates_io_database/src/schema.patch
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
- pub struct Tsvector;
+ pub use diesel_full_text_search::Tsvector;
}

diesel::table! {
@@ -25,7 +23,7 @@
/// (Automatically generated by Diesel.)
Expand Down Expand Up @@ -53,7 +53,7 @@
/// Its SQL type is `Int4`.
@@ -722,6 +714,24 @@
}

diesel::table! {
+ /// Representation of the `recent_crate_downloads` view.
+ ///
Expand Down
2 changes: 2 additions & 0 deletions crates/crates_io_database/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,8 @@ diesel::table! {
///
/// (Automatically generated by Diesel.)
id -> Int4,
/// Whether this email is the primary email address for the user.
is_primary -> Bool,
/// The `token` column of the `emails` table.
///
/// Its SQL type is `Text`.
Expand Down
Loading
Loading