diff --git a/backend/src/api/model/event.rs b/backend/src/api/model/event.rs index fa356116e..d5475797e 100644 --- a/backend/src/api/model/event.rs +++ b/backend/src/api/model/event.rs @@ -666,7 +666,11 @@ impl LoadableAsset for AuthorizedEvent { } fn table_name() -> &'static str { - "events" + "all_events" + } + + fn alias() -> Option<&'static str> { + Some("events") } fn sort_clauses(_column: &str) -> (&str, &str) { diff --git a/backend/src/api/model/series.rs b/backend/src/api/model/series.rs index 135c3286f..3e176e188 100644 --- a/backend/src/api/model/series.rs +++ b/backend/src/api/model/series.rs @@ -406,10 +406,14 @@ impl LoadableAsset for Series { "series" } + fn alias() -> Option<&'static str> { + None + } + fn sort_clauses(column: &str) -> (&str, &str) { match column { - "count(events.id)" => ( - "left join events on events.series = series.id", + "count(all_events.id)" => ( + "left join all_events on all_events.series = series.id", "group by series.id", ), _ => ("", ""), diff --git a/backend/src/api/model/shared.rs b/backend/src/api/model/shared.rs index 8fc229439..98bc2c3a5 100644 --- a/backend/src/api/model/shared.rs +++ b/backend/src/api/model/shared.rs @@ -112,7 +112,7 @@ define_sort_column_and_order!( Title => "title", Created => "created", Updated => "updated", - EventCount => "count(events.id)", + EventCount => "count(all_events.id)", }; pub struct SeriesSortOrder ); @@ -164,6 +164,7 @@ pub type AssetMapping = ResourceMapping; pub trait LoadableAsset: FromDb { fn selection() -> (String, ::RowMapping); fn table_name() -> &'static str; + fn alias() -> Option<&'static str>; /// Returns custom `join` and `group by` clauses that might be required /// for ordering by certain columns. fn sort_clauses(column: &str) -> (&str, &str); @@ -201,6 +202,13 @@ where }; let table = T::table_name(); + let alias = T::alias(); + + let table_alias = match alias { + Some(a) => format!("{table} as {a}"), + None => table.to_string(), + }; + let table = alias.unwrap_or(table); // We need to know the item count before querying the actual items, // to check if the offset is too high. If it is, it's set to the maximum. @@ -217,7 +225,7 @@ where let (join_clause, group_by_clause) = T::sort_clauses(&sort_column); let query = format!( - "select {selection} from {table} \ + "select {selection} from {table_alias} \ {join_clause} \ {acl_filter} \ {group_by_clause} \ @@ -228,7 +236,7 @@ where // Execute query let items = context.db.query_mapped(&query, args, |row| { - // Retrieve actual event data + // Retrieve actual row data T::from_row(&row, mapping) }).await?;