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

Bring back MySQL support #350

Merged
merged 11 commits into from
Sep 19, 2023
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion apps/backend/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ryot"
version = "2.17.4"
version = "2.17.5"
edition = "2021"
repository = "https://github.com/IgnisDa/ryot"
license = "GPL-V3"
Expand Down
23 changes: 1 addition & 22 deletions apps/backend/src/entities/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ use sea_orm::{entity::prelude::*, ActiveValue};
use serde::{Deserialize, Serialize};

use crate::{
entities::prelude::PartialMetadata,
entities::{partial_metadata, prelude::PartialMetadata},
migrator::{MetadataLot, MetadataSource},
models::media::{MediaSpecifics, MetadataImages, MetadataVideos},
};

use super::partial_metadata;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize, Default)]
#[sea_orm(table_name = "metadata")]
pub struct Model {
Expand Down Expand Up @@ -172,23 +170,4 @@ impl ActiveModelBehavior for ActiveModel {
}
Ok(model)
}

async fn after_delete<C>(self, db: &C) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
let copied = self.clone();
if let Some(m) = PartialMetadata::find()
.filter(partial_metadata::Column::Identifier.eq(copied.identifier.unwrap()))
.filter(partial_metadata::Column::Lot.eq(copied.lot.unwrap()))
.filter(partial_metadata::Column::Source.eq(copied.source.unwrap()))
.one(db)
.await?
{
let mut m: partial_metadata::ActiveModel = m.into();
m.metadata_id = ActiveValue::Set(None);
m.update(db).await?;
}
Ok(self)
}
}
15 changes: 9 additions & 6 deletions apps/backend/src/migrator/m20230901_create_partial_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ use serde::{Deserialize, Serialize};

use super::{m20230901_create_metadata_group::MetadataGroup, Metadata};

pub static PARTIAL_METADATA_FK_1: &str = "fk-metadata_id-partial-metadata_id";
pub static PARTIAL_METADATA_TO_METADATA_GROUP_FK_1: &str =
"partial-metadata-to-metadata-group-fk-1";
pub static PARTIAL_METADATA_TO_METADATA_GROUP_FK_2: &str =
"partial-metadata-to-metadata-group-fk-2";

#[derive(DeriveMigrationName)]
pub struct Migration;

Expand Down Expand Up @@ -80,7 +86,7 @@ impl MigrationTrait for Migration {
)
.foreign_key(
ForeignKey::create()
.name("fk-metadata_id-partial-metadata_id")
.name(PARTIAL_METADATA_FK_1)
.from(PartialMetadata::Table, PartialMetadata::MetadataId)
.to(Metadata::Table, Metadata::Id)
.on_delete(ForeignKeyAction::Cascade)
Expand Down Expand Up @@ -145,7 +151,6 @@ impl MigrationTrait for Migration {
MetadataToPartialMetadata::PartialMetadataId,
)
.to(PartialMetadata::Table, PartialMetadata::Id)
// FIXME: Use `SetNull` and also remove `after_save` sea-orm hook for `metadata`
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
Expand Down Expand Up @@ -179,7 +184,7 @@ impl MigrationTrait for Migration {
)
.foreign_key(
ForeignKey::create()
.name("fk_partial-metadata-to-metadata-group_id-metadata-partial-metadata_id")
.name(PARTIAL_METADATA_TO_METADATA_GROUP_FK_1)
.from(
PartialMetadataToMetadataGroup::Table,
PartialMetadataToMetadataGroup::PartialMetadataId,
Expand All @@ -190,9 +195,7 @@ impl MigrationTrait for Migration {
)
.foreign_key(
ForeignKey::create()
.name(
"fk_partial-metadata-to-metadata-group-group_id-metadata-group_id",
)
.name(PARTIAL_METADATA_TO_METADATA_GROUP_FK_2)
.from(
PartialMetadataToMetadataGroup::Table,
PartialMetadataToMetadataGroup::MetadataGroupId,
Expand Down
85 changes: 85 additions & 0 deletions apps/backend/src/migrator/m20230919_change_foreign_keys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use sea_orm::{DatabaseBackend, Statement};
use sea_orm_migration::prelude::*;

use super::m20230901_create_partial_metadata::{
PARTIAL_METADATA_FK_1, PARTIAL_METADATA_TO_METADATA_GROUP_FK_1,
PARTIAL_METADATA_TO_METADATA_GROUP_FK_2,
};

#[derive(DeriveMigrationName)]
pub struct Migration;

async fn change_fk_definition<'a>(
manager: &SchemaManager<'a>,
table_name: &str,
old_name: &str,
new_name: &str,
fk_from: &str,
fk_to: &str,
action: &str,
) -> Result<(), DbErr> {
let db = manager.get_connection();
let stmt = Statement::from_sql_and_values(
manager.get_database_backend(),
"SELECT count(*) > 0 FROM information_schema.table_constraints WHERE constraint_name=$1 AND table_name=$2",
[old_name.into(), table_name.into()],
);
if let Some(row) = db.query_one(stmt).await? {
let has_fk = row.try_get_by_index::<bool>(0).unwrap();
if has_fk {
db
.execute_unprepared(&format!(
r#"
ALTER TABLE {table_name}
DROP CONSTRAINT "{old_name}",
ADD CONSTRAINT "{new_name}" FOREIGN KEY ({fk_from}) REFERENCES {fk_to}(id) ON UPDATE CASCADE ON DELETE {action};
"#
))
.await?;
}
}
Ok(())
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
if matches!(manager.get_database_backend(), DatabaseBackend::Postgres) {
change_fk_definition(
manager,
"partial_metadata_to_metadata_group",
"fk_partial-metadata-to-metadata-group-group_id-metadata-group_i",
PARTIAL_METADATA_TO_METADATA_GROUP_FK_1,
"metadata_group_id",
"metadata_group",
"CASCADE",
)
.await?;
change_fk_definition(
manager,
"partial_metadata_to_metadata_group",
"fk_partial-metadata-to-metadata-group_id-metadata-partial-metad",
PARTIAL_METADATA_TO_METADATA_GROUP_FK_2,
"partial_metadata_id",
"partial_metadata",
"CASCADE",
)
.await?;
change_fk_definition(
manager,
"partial_metadata",
PARTIAL_METADATA_FK_1,
PARTIAL_METADATA_FK_1,
"metadata_id",
"metadata",
"SET NULL",
)
.await?;
}
Ok(())
}

async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {
Ok(())
}
}
2 changes: 2 additions & 0 deletions apps/backend/src/migrator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ mod m20230911_add_is_nsfw_to_metadata;
mod m20230912_add_last_processed_for_calendar_to_metadata;
mod m20230912_create_calendar_event;
mod m20230919_add_num_times_updated_field_to_seen;
mod m20230919_change_foreign_keys;

pub use m20230410_create_metadata::{Metadata, MetadataLot, MetadataSource};
pub use m20230417_create_user::{UserLot, UserToMetadata};
Expand Down Expand Up @@ -71,6 +72,7 @@ impl MigratorTrait for Migrator {
Box::new(m20230912_add_last_processed_for_calendar_to_metadata::Migration),
Box::new(m20230912_create_calendar_event::Migration),
Box::new(m20230919_add_num_times_updated_field_to_seen::Migration),
Box::new(m20230919_change_foreign_keys::Migration),
]
}
}
22 changes: 22 additions & 0 deletions apps/backend/src/miscellaneous/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2916,6 +2916,28 @@ impl MiscellaneousService {
creator.delete(&self.db).await.ok();
}
}
tracing::trace!("Cleaning up partial metadata without associated metadata");
let mut all_partial_metadata = PartialMetadataModel::find().stream(&self.db).await?;
while let Some(partial_metadata) = all_partial_metadata.try_next().await? {
let num_associations = MetadataToPartialMetadata::find()
.filter(
metadata_to_partial_metadata::Column::PartialMetadataId.eq(partial_metadata.id),
)
.count(&self.db)
.await
.unwrap();
let num_group_associations = PartialMetadataToMetadataGroup::find()
.filter(
partial_metadata_to_metadata_group::Column::PartialMetadataId
.eq(partial_metadata.id),
)
.count(&self.db)
.await
.unwrap();
if num_associations + num_group_associations == 0 {
partial_metadata.delete(&self.db).await.ok();
}
}
Ok(())
}

Expand Down