Skip to content

Commit 70c5c7e

Browse files
authored
Person related changes (#1240)
* chore(migrations): change order of variants * feat(migrations): add new column for person to track number of associated metadata * feat(models/database): add new column to entity * feat(migrations): change name and defn of column * chore(frontend): change order of args * feat(backend): adapt to new db schema * chore(frontend): adapt to new gql schema * fix(frontend): display correct count * feat(migrations): add new generated columns * feat(backend): add support for new columns * feat(frontend): use new variables for associations
1 parent 822a22b commit 70c5c7e

File tree

14 files changed

+120
-55
lines changed

14 files changed

+120
-55
lines changed

apps/frontend/app/components/media.tsx

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -348,35 +348,24 @@ export const PersonDisplayItem = (props: {
348348
}) => {
349349
const { ref, inViewport } = useInViewport();
350350
const { data: personDetails, isLoading: isPersonDetailsLoading } = useQuery({
351+
enabled: inViewport,
351352
queryKey: queryFactory.media.personDetails(props.personId).queryKey,
352353
queryFn: async () => {
353354
return clientGqlService
354355
.request(PersonDetailsDocument, props)
355356
.then((data) => data.personDetails);
356357
},
357-
enabled: inViewport,
358358
});
359359
const { data: userPersonDetails } = useQuery({
360+
enabled: inViewport,
360361
queryKey: queryFactory.media.userPersonDetails(props.personId).queryKey,
361362
queryFn: async () => {
362363
return clientGqlService
363364
.request(UserPersonDetailsDocument, props)
364365
.then((data) => data.userPersonDetails);
365366
},
366-
enabled: inViewport,
367367
});
368368

369-
const metadataCount =
370-
personDetails?.associatedMetadata.reduce(
371-
(sum, content) => sum + content.items.length,
372-
0,
373-
) || 0;
374-
const metadataGroupCount =
375-
personDetails?.associatedMetadataGroups.reduce(
376-
(sum, content) => sum + content.items.length,
377-
0,
378-
) || 0;
379-
380369
return (
381370
<BaseMediaDisplayItem
382371
innerRef={ref}
@@ -391,7 +380,7 @@ export const PersonDisplayItem = (props: {
391380
labels={{
392381
right: props.rightLabel,
393382
left: personDetails
394-
? `${metadataCount + metadataGroupCount} items`
383+
? `${personDetails.details.associatedEntityCount} items`
395384
: undefined,
396385
}}
397386
/>

apps/frontend/app/routes/_dashboard.media.groups.$action.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export type SearchParams = {
7272
};
7373

7474
const defaultFilters = {
75-
sortBy: PersonAndMetadataGroupsSortBy.MediaItems,
75+
sortBy: PersonAndMetadataGroupsSortBy.AssociatedEntityCount,
7676
orderBy: GraphqlSortOrder.Desc,
7777
};
7878

apps/frontend/app/routes/_dashboard.media.people.$action.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ export type SearchParams = {
7070
};
7171

7272
const defaultFilters = {
73-
sortBy: PersonAndMetadataGroupsSortBy.MediaItems,
73+
sortBy: PersonAndMetadataGroupsSortBy.AssociatedEntityCount,
7474
orderBy: GraphqlSortOrder.Desc,
7575
};
7676

apps/frontend/app/routes/_dashboard.media.people.item.$id._index.tsx

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
PersonDetailsDocument,
1717
UserPersonDetailsDocument,
1818
} from "@ryot/generated/graphql/backend/graphql";
19-
import { parseParameters, parseSearchQuery, sum } from "@ryot/ts-utils";
19+
import { parseParameters, parseSearchQuery } from "@ryot/ts-utils";
2020
import {
2121
IconDeviceTv,
2222
IconInfoCircle,
@@ -94,12 +94,10 @@ export default function Page() {
9494
.at(0) || null,
9595
);
9696

97-
const totalMetadata = sum(
98-
loaderData.personDetails.associatedMetadata.map((c) => c.count),
99-
);
100-
const totalMetadataGroups = sum(
101-
loaderData.personDetails.associatedMetadataGroups.map((c) => c.count),
102-
);
97+
const totalMetadata =
98+
loaderData.personDetails.details.associatedMetadataCount;
99+
const totalMetadataGroups =
100+
loaderData.personDetails.details.associatedMetadataGroupsCount;
103101
const additionalPersonDetails = [
104102
totalMetadata ? `${totalMetadata} media items` : null,
105103
totalMetadataGroups ? `${totalMetadataGroups} groups` : null,

crates/migrations/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ mod m20250122_changes_for_issue_1188;
3131
mod m20250126_changes_for_issue_1201;
3232
mod m20250201_changes_for_issue_1211;
3333
mod m20250204_changes_for_issue_1231;
34+
mod m20250208_changes_for_issue_1233;
3435

3536
pub use m20230404_create_user::User as AliasedUser;
3637
pub use m20230410_create_metadata::Metadata as AliasedMetadata;
@@ -83,6 +84,7 @@ impl MigratorTrait for Migrator {
8384
Box::new(m20250126_changes_for_issue_1201::Migration),
8485
Box::new(m20250201_changes_for_issue_1211::Migration),
8586
Box::new(m20250204_changes_for_issue_1231::Migration),
87+
Box::new(m20250208_changes_for_issue_1233::Migration),
8688
]
8789
}
8890
}

crates/migrations/src/m20230413_create_person.rs

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,34 @@ pub struct Migration;
77

88
pub static METADATA_TO_PERSON_PRIMARY_KEY: &str = "pk-media-item_person";
99
pub static PERSON_IDENTIFIER_UNIQUE_KEY: &str = "person-identifier-source__unique_index";
10+
pub static PERSON_ASSOCIATED_METADATA_COUNT_GENERATED_SQL: &str = r#"GENERATED ALWAYS AS (COALESCE(JSONB_ARRAY_LENGTH("state_changes"->'metadata_associated'), 0)) STORED"#;
11+
pub static PERSON_ASSOCIATED_METADATA_GROUPS_COUNT_GENERATED_SQL: &str = r#"GENERATED ALWAYS AS (COALESCE(JSONB_ARRAY_LENGTH("state_changes"->'metadata_groups_associated'), 0)) STORED"#;
12+
pub static PERSON_ASSOCIATED_ENTITY_COUNT_GENERATED_SQL: &str = r#"GENERATED ALWAYS AS (COALESCE(JSONB_ARRAY_LENGTH("state_changes"->'metadata_associated'), 0) + COALESCE(JSONB_ARRAY_LENGTH("state_changes"->'metadata_groups_associated'), 0)) STORED"#;
1013

1114
#[derive(Iden)]
1215
pub enum Person {
13-
Table,
1416
Id,
15-
Identifier,
16-
Source,
17-
CreatedOn,
18-
LastUpdatedOn,
1917
Name,
20-
Description,
18+
Table,
19+
Place,
20+
Source,
2121
Gender,
22+
Images,
23+
Website,
2224
BirthDate,
25+
CreatedOn,
2326
DeathDate,
24-
// The place of origin
25-
Place,
26-
Website,
27-
Images,
2827
IsPartial,
29-
SourceSpecifics,
30-
StateChanges,
3128
SourceUrl,
29+
Identifier,
30+
Description,
31+
StateChanges,
32+
LastUpdatedOn,
3233
AlternateNames,
34+
SourceSpecifics,
35+
AssociatedEntityCount,
36+
AssociatedMetadataCount,
37+
AssociatedMetadataGroupsCount,
3338
}
3439

3540
#[derive(Iden)]
@@ -87,6 +92,18 @@ impl MigrationTrait for Migration {
8792
.col(ColumnDef::new(Person::StateChanges).json_binary())
8893
.col(ColumnDef::new(Person::SourceUrl).text())
8994
.col(ColumnDef::new(Person::AlternateNames).array(ColumnType::Text))
95+
.col(
96+
ColumnDef::new(Person::AssociatedMetadataCount)
97+
.integer()
98+
.not_null()
99+
.extra(PERSON_ASSOCIATED_METADATA_COUNT_GENERATED_SQL),
100+
)
101+
.col(
102+
ColumnDef::new(Person::AssociatedMetadataGroupsCount)
103+
.integer()
104+
.not_null()
105+
.extra(PERSON_ASSOCIATED_METADATA_GROUPS_COUNT_GENERATED_SQL),
106+
)
90107
.to_owned(),
91108
)
92109
.await?;
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use sea_orm_migration::prelude::*;
2+
3+
use crate::m20230413_create_person::{
4+
PERSON_ASSOCIATED_ENTITY_COUNT_GENERATED_SQL, PERSON_ASSOCIATED_METADATA_COUNT_GENERATED_SQL,
5+
PERSON_ASSOCIATED_METADATA_GROUPS_COUNT_GENERATED_SQL,
6+
};
7+
8+
#[derive(DeriveMigrationName)]
9+
pub struct Migration;
10+
11+
#[async_trait::async_trait]
12+
impl MigrationTrait for Migration {
13+
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
14+
let db = manager.get_connection();
15+
if !manager
16+
.has_column("person", "associated_metadata_count")
17+
.await?
18+
{
19+
db.execute_unprepared(&format!(
20+
r#"ALTER TABLE "person" ADD COLUMN "associated_metadata_count" INTEGER NOT NULL {}"#,
21+
PERSON_ASSOCIATED_METADATA_COUNT_GENERATED_SQL
22+
))
23+
.await?;
24+
}
25+
if !manager
26+
.has_column("person", "associated_metadata_groups_count")
27+
.await?
28+
{
29+
db.execute_unprepared(&format!(
30+
r#"ALTER TABLE "person" ADD COLUMN "associated_metadata_groups_count" INTEGER NOT NULL {}"#,
31+
PERSON_ASSOCIATED_METADATA_GROUPS_COUNT_GENERATED_SQL
32+
))
33+
.await?;
34+
}
35+
if !manager
36+
.has_column("person", "associated_entity_count")
37+
.await?
38+
{
39+
db.execute_unprepared(&format!(
40+
r#"ALTER TABLE "person" ADD COLUMN "associated_entity_count" INTEGER NOT NULL {}"#,
41+
PERSON_ASSOCIATED_ENTITY_COUNT_GENERATED_SQL
42+
))
43+
.await?;
44+
}
45+
Ok(())
46+
}
47+
48+
async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {
49+
Ok(())
50+
}
51+
}

crates/models/database/src/person.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,15 @@ pub struct Model {
2929
pub display_images: Vec<String>,
3030
pub description: Option<String>,
3131
pub last_updated_on: DateTimeUtc,
32+
pub associated_entity_count: i32,
3233
pub birth_date: Option<NaiveDate>,
3334
pub death_date: Option<NaiveDate>,
35+
pub associated_metadata_count: i32,
3436
#[sea_orm(column_type = "Json")]
3537
#[graphql(skip)]
3638
pub images: Option<Vec<MetadataImage>>,
3739
pub alternate_names: Option<Vec<String>>,
40+
pub associated_metadata_groups_count: i32,
3841
#[graphql(skip)]
3942
pub state_changes: Option<PersonStateChanges>,
4043
#[graphql(skip)]

crates/models/media/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1281,7 +1281,7 @@ pub enum PersonAndMetadataGroupsSortBy {
12811281
#[default]
12821282
Name,
12831283
Random,
1284-
MediaItems,
1284+
AssociatedEntityCount,
12851285
}
12861286

12871287
#[derive(Debug, Hash, Serialize, Deserialize, Enum, Clone, Copy, Eq, PartialEq, Default)]

crates/utils/dependent/src/lib.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2988,7 +2988,7 @@ pub async fn user_metadata_groups_list(
29882988
Some(ord) => (
29892989
match ord.by {
29902990
PersonAndMetadataGroupsSortBy::Random => Expr::expr(Func::random()),
2991-
PersonAndMetadataGroupsSortBy::MediaItems => metadata_group_parts_col,
2991+
PersonAndMetadataGroupsSortBy::AssociatedEntityCount => metadata_group_parts_col,
29922992
PersonAndMetadataGroupsSortBy::Name => Expr::col(metadata_group::Column::Title),
29932993
},
29942994
graphql_to_db_order(ord.order),
@@ -3074,15 +3074,18 @@ pub async fn user_people_list(
30743074
.unwrap_or(1)
30753075
.try_into()
30763076
.unwrap();
3077-
let alias = "media_count";
3078-
let media_items_col = Expr::col(Alias::new(alias));
30793077
let (order_by, sort_order) = match input.sort {
3080-
None => (media_items_col, Order::Desc),
3078+
None => (
3079+
Expr::col(person::Column::AssociatedEntityCount),
3080+
Order::Desc,
3081+
),
30813082
Some(ord) => (
30823083
match ord.by {
3083-
PersonAndMetadataGroupsSortBy::MediaItems => media_items_col,
30843084
PersonAndMetadataGroupsSortBy::Random => Expr::expr(Func::random()),
30853085
PersonAndMetadataGroupsSortBy::Name => Expr::col(person::Column::Name),
3086+
PersonAndMetadataGroupsSortBy::AssociatedEntityCount => {
3087+
Expr::col(person::Column::AssociatedEntityCount)
3088+
}
30863089
},
30873090
graphql_to_db_order(ord.order),
30883091
),
@@ -3108,13 +3111,6 @@ pub async fn user_people_list(
31083111
)
31093112
},
31103113
)
3111-
.column_as(
3112-
Expr::expr(Func::count(Expr::col((
3113-
Alias::new("metadata_to_person"),
3114-
metadata_to_person::Column::MetadataId,
3115-
)))),
3116-
alias,
3117-
)
31183114
.filter(user_to_entity::Column::UserId.eq(user_id))
31193115
.left_join(MetadataToPerson)
31203116
.inner_join(UserToEntity)

0 commit comments

Comments
 (0)