Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove user_to_collection table #1000

Merged
merged 8 commits into from
Sep 3, 2024
3 changes: 2 additions & 1 deletion crates/migrations/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ mod m20240827_zz_changes_for_daily_user_activity;
mod m20240828_add_last_login_on_column_to_user;
mod m20240828_zz_add_columns_to_daily_user_activity;
mod m20240829_change_structure_for_exercise_extra_information;
mod m20240903_add_changes_for_user_to_collection_removal;

pub use m20230410_create_metadata::Metadata as AliasedMetadata;
pub use m20230413_create_person::Person as AliasedPerson;
Expand All @@ -43,7 +44,6 @@ pub use m20230505_create_review::Review as AliasedReview;
pub use m20230822_create_exercise::Exercise as AliasedExercise;
pub use m20231016_create_collection_to_entity::CollectionToEntity as AliasedCollectionToEntity;
pub use m20231017_create_user_to_entity::UserToEntity as AliasedUserToEntity;
pub use m20240509_create_user_to_collection::UserToCollection as AliasedUserToCollection;

pub struct Migrator;

Expand Down Expand Up @@ -79,6 +79,7 @@ impl MigratorTrait for Migrator {
Box::new(m20240828_add_last_login_on_column_to_user::Migration),
Box::new(m20240828_zz_add_columns_to_daily_user_activity::Migration),
Box::new(m20240829_change_structure_for_exercise_extra_information::Migration),
Box::new(m20240903_add_changes_for_user_to_collection_removal::Migration),
]
}
}
30 changes: 26 additions & 4 deletions crates/migrations/src/m20231017_create_user_to_entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use sea_orm_migration::prelude::*;
use super::{
m20230410_create_metadata::Metadata, m20230413_create_person::Person,
m20230417_create_user::User, m20230501_create_metadata_group::MetadataGroup,
m20230822_create_exercise::Exercise,
m20230504_create_collection::Collection, m20230822_create_exercise::Exercise,
};

#[derive(DeriveMigrationName)]
Expand All @@ -13,7 +13,9 @@ pub struct Migration;
pub static PERSON_FK_NAME: &str = "user_to_entity-fk4";
pub static PERSON_INDEX_NAME: &str = "user_to_entity-uqi3";
pub static METADATA_GROUP_FK_NAME: &str = "user_to_entity-fk5";
pub static COLLECTION_FK_NAME: &str = "user_to_entity-fk6";
pub static METADATA_GROUP_INDEX_NAME: &str = "user_to_entity-uqi4";
pub static COLLECTION_INDEX_NAME: &str = "user_to_entity-uqi5";
pub static CONSTRAINT_SQL: &str = indoc! { r#"
ALTER TABLE "user_to_entity" DROP CONSTRAINT IF EXISTS "user_to_entity__ensure_one_entity";
ALTER TABLE "user_to_entity"
Expand All @@ -22,7 +24,8 @@ pub static CONSTRAINT_SQL: &str = indoc! { r#"
(CASE WHEN "metadata_id" IS NOT NULL THEN 1 ELSE 0 END) +
(CASE WHEN "person_id" IS NOT NULL THEN 1 ELSE 0 END) +
(CASE WHEN "exercise_id" IS NOT NULL THEN 1 ELSE 0 END) +
(CASE WHEN "metadata_group_id" IS NOT NULL THEN 1 ELSE 0 END)
(CASE WHEN "metadata_group_id" IS NOT NULL THEN 1 ELSE 0 END) +
(CASE WHEN "collection_id" IS NOT NULL THEN 1 ELSE 0 END)
= 1
);
"# };
Expand All @@ -31,8 +34,6 @@ pub static CONSTRAINT_SQL: &str = indoc! { r#"
/// - the user has it in their seen history
/// - added it to a collection
/// - has reviewed it
/// - owns it
/// - added a reminder
#[derive(Iden)]
pub enum UserToEntity {
Table,
Expand All @@ -46,6 +47,7 @@ pub enum UserToEntity {
ExerciseId,
PersonId,
MetadataGroupId,
CollectionId,
// specifics
ExerciseExtraInformation,
ExerciseNumTimesInteracted,
Expand Down Expand Up @@ -80,6 +82,7 @@ impl MigrationTrait for Migration {
.col(ColumnDef::new(UserToEntity::MetadataGroupId).text())
.col(ColumnDef::new(UserToEntity::PersonId).text())
.col(ColumnDef::new(UserToEntity::MetadataId).text())
.col(ColumnDef::new(UserToEntity::CollectionId).text())
.col(ColumnDef::new(UserToEntity::UserId).text().not_null())
.col(
ColumnDef::new(UserToEntity::Id)
Expand Down Expand Up @@ -128,6 +131,14 @@ impl MigrationTrait for Migration {
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.foreign_key(
ForeignKey::create()
.name(COLLECTION_FK_NAME)
.from(UserToEntity::Table, UserToEntity::CollectionId)
.to(Collection::Table, MetadataGroup::Id)
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned(),
)
.await?;
Expand Down Expand Up @@ -175,6 +186,17 @@ impl MigrationTrait for Migration {
.to_owned(),
)
.await?;
manager
.create_index(
Index::create()
.unique()
.name(COLLECTION_INDEX_NAME)
.table(UserToEntity::Table)
.col(UserToEntity::UserId)
.col(UserToEntity::CollectionId)
.to_owned(),
)
.await?;
db.execute_unprepared(CONSTRAINT_SQL).await?;
Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// FIXME: Delete this migration
use sea_orm_migration::prelude::*;

use super::{m20230417_create_user::User, m20230504_create_collection::Collection};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use sea_orm_migration::prelude::*;

use crate::m20231017_create_user_to_entity::CONSTRAINT_SQL;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
let db = manager.get_connection();
if !manager
.has_column("user_to_entity", "collection_id")
.await?
{
db.execute_unprepared(
r#"
ALTER TABLE "user_to_entity" ADD COLUMN "collection_id" TEXT;
ALTER TABLE "user_to_entity" ADD CONSTRAINT "user_to_entity-fk6" FOREIGN KEY ("collection_id") REFERENCES "collection" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
CREATE UNIQUE INDEX "user_to_entity-uqi5" ON "user_to_entity" ("user_id", "collection_id");
"#,
)
.await?;
db.execute_unprepared(CONSTRAINT_SQL).await?;
}
if manager.has_table("user_to_collection").await? {
db.execute_unprepared(
r#"
INSERT INTO "user_to_entity" ("user_id", "collection_id") SELECT "user_id", "collection_id" FROM "user_to_collection";
DROP TABLE "user_to_collection";
"#,
)
.await?;
}
Ok(())
}

async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {
Ok(())
}
}
8 changes: 4 additions & 4 deletions crates/models/database/src/collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ pub enum Relation {
on_delete = "Cascade"
)]
User,
#[sea_orm(has_many = "super::user_to_collection::Entity")]
UserToCollection,
#[sea_orm(has_many = "super::user_to_entity::Entity")]
UserToEntity,
}

impl Related<super::collection_to_entity::Entity> for Entity {
Expand All @@ -59,9 +59,9 @@ impl Related<super::user::Entity> for Entity {
}
}

impl Related<super::user_to_collection::Entity> for Entity {
impl Related<super::user_to_entity::Entity> for Entity {
fn to() -> RelationDef {
Relation::UserToCollection.def()
Relation::UserToEntity.def()
}
}

Expand Down
1 change: 0 additions & 1 deletion crates/models/database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,5 @@ pub mod review;
pub mod seen;
pub mod user;
pub mod user_measurement;
pub mod user_to_collection;
pub mod user_to_entity;
pub mod workout;
1 change: 0 additions & 1 deletion crates/models/database/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,5 @@ pub use super::review::Entity as Review;
pub use super::seen::Entity as Seen;
pub use super::user::Entity as User;
pub use super::user_measurement::Entity as UserMeasurement;
pub use super::user_to_collection::Entity as UserToCollection;
pub use super::user_to_entity::Entity as UserToEntity;
pub use super::workout::Entity as Workout;
17 changes: 0 additions & 17 deletions crates/models/database/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@ pub enum Relation {
Seen,
#[sea_orm(has_many = "super::user_measurement::Entity")]
UserMeasurement,
#[sea_orm(has_many = "super::user_to_collection::Entity")]
UserToCollection,
#[sea_orm(has_many = "super::user_to_entity::Entity")]
UserToEntity,
#[sea_orm(has_many = "super::workout::Entity")]
Expand Down Expand Up @@ -108,12 +106,6 @@ impl Related<super::user_measurement::Entity> for Entity {
}
}

impl Related<super::user_to_collection::Entity> for Entity {
fn to() -> RelationDef {
Relation::UserToCollection.def()
}
}

impl Related<super::user_to_entity::Entity> for Entity {
fn to() -> RelationDef {
Relation::UserToEntity.def()
Expand All @@ -126,15 +118,6 @@ impl Related<super::workout::Entity> for Entity {
}
}

impl Related<super::collection::Entity> for Entity {
fn to() -> RelationDef {
super::user_to_collection::Relation::Collection.def()
}
fn via() -> Option<RelationDef> {
Some(super::user_to_collection::Relation::User.def().rev())
}
}

#[async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(mut self, _db: &C, _insert: bool) -> Result<Self, DbErr>
Expand Down
46 changes: 0 additions & 46 deletions crates/models/database/src/user_to_collection.rs

This file was deleted.

15 changes: 15 additions & 0 deletions crates/models/database/src/user_to_entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub struct Model {
pub person_id: Option<String>,
pub metadata_id: Option<String>,
pub exercise_id: Option<String>,
pub collection_id: Option<String>,
pub exercise_extra_information: Option<UserToExerciseExtraInformation>,
pub exercise_num_times_interacted: Option<i32>,
#[graphql(skip)]
Expand All @@ -31,6 +32,14 @@ pub struct Model {

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::collection::Entity",
from = "Column::CollectionId",
to = "super::collection::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
Collection,
#[sea_orm(
belongs_to = "super::exercise::Entity",
from = "Column::ExerciseId",
Expand Down Expand Up @@ -73,6 +82,12 @@ pub enum Relation {
User,
}

impl Related<super::collection::Entity> for Entity {
fn to() -> RelationDef {
Relation::Collection.def()
}
}

impl Related<super::exercise::Entity> for Entity {
fn to() -> RelationDef {
Relation::Exercise.def()
Expand Down
27 changes: 12 additions & 15 deletions crates/services/collection/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use database_models::{
collection, collection_to_entity,
prelude::{
Collection, CollectionToEntity, Exercise, Metadata, MetadataGroup, Person, User,
UserToCollection, Workout,
UserToEntity, Workout,
},
user_to_collection,
user_to_entity,
};
use database_utils::{
add_entity_to_collection, create_or_update_collection, ilike_sql, item_reviews,
Expand All @@ -26,7 +26,7 @@ use media_models::{
};
use migrations::{
AliasedCollection, AliasedCollectionToEntity, AliasedExercise, AliasedMetadata,
AliasedMetadataGroup, AliasedPerson, AliasedUser, AliasedUserToCollection,
AliasedMetadataGroup, AliasedPerson, AliasedUser, AliasedUserToEntity,
};
use sea_orm::{
ColumnTrait, DatabaseConnection, EntityTrait, ItemsAndPagesNumber, Iterable, JoinType,
Expand Down Expand Up @@ -76,7 +76,7 @@ impl CollectionService {
}
}
let collaborators_subquery = Query::select()
.from(UserToCollection)
.from(UserToEntity)
.expr(
Func::cust(JsonAgg).arg(
Func::cust(JsonBuildObject)
Expand All @@ -89,16 +89,13 @@ impl CollectionService {
.join(
JoinType::InnerJoin,
AliasedUser::Table,
Expr::col((
AliasedUserToCollection::Table,
AliasedUserToCollection::UserId,
))
.equals((AliasedUser::Table, AliasedUser::Id)),
Expr::col((AliasedUserToEntity::Table, AliasedUserToEntity::UserId))
.equals((AliasedUser::Table, AliasedUser::Id)),
)
.and_where(
Expr::col((
AliasedUserToCollection::Table,
AliasedUserToCollection::CollectionId,
AliasedUserToEntity::Table,
AliasedUserToEntity::CollectionId,
))
.equals((AliasedCollection::Table, AliasedCollection::Id)),
)
Expand All @@ -116,8 +113,8 @@ impl CollectionService {
AliasedCollectionToEntity::CollectionId,
))
.equals((
AliasedUserToCollection::Table,
AliasedUserToCollection::CollectionId,
AliasedUserToEntity::Table,
AliasedUserToEntity::CollectionId,
)),
)
.to_owned();
Expand Down Expand Up @@ -162,8 +159,8 @@ impl CollectionService {
)
.order_by_desc(collection::Column::LastUpdatedOn)
.left_join(User)
.left_join(UserToCollection)
.filter(user_to_collection::Column::UserId.eq(user_id))
.left_join(UserToEntity)
.filter(user_to_entity::Column::UserId.eq(user_id))
.into_model::<CollectionItem>()
.all(&self.db)
.await
Expand Down
Loading