1 use crate::structs::CustomEmojiView;
2 use diesel::{result::Error, ExpressionMethods, JoinOnDsl, NullableExpressionMethods, QueryDsl};
3 use diesel_async::RunQueryDsl;
5 newtypes::{CustomEmojiId, LocalSiteId},
6 schema::{custom_emoji, custom_emoji_keyword},
7 source::{custom_emoji::CustomEmoji, custom_emoji_keyword::CustomEmojiKeyword},
8 utils::{get_conn, DbPool},
10 use std::collections::HashMap;
12 type CustomEmojiTuple = (CustomEmoji, Option<CustomEmojiKeyword>);
14 impl CustomEmojiView {
15 pub async fn get(pool: &mut DbPool<'_>, emoji_id: CustomEmojiId) -> Result<Self, Error> {
16 let conn = &mut get_conn(pool).await?;
17 let emojis = custom_emoji::table
20 custom_emoji_keyword::table.on(custom_emoji_keyword::custom_emoji_id.eq(custom_emoji::id)),
23 custom_emoji::all_columns,
24 custom_emoji_keyword::all_columns.nullable(), // (or all the columns if you want)
26 .load::<CustomEmojiTuple>(conn)
28 if let Some(emoji) = CustomEmojiView::from_tuple_to_vec(emojis)
34 Err(diesel::result::Error::NotFound)
39 pool: &mut DbPool<'_>,
40 for_local_site_id: LocalSiteId,
41 ) -> Result<Vec<Self>, Error> {
42 let conn = &mut get_conn(pool).await?;
43 let emojis = custom_emoji::table
44 .filter(custom_emoji::local_site_id.eq(for_local_site_id))
46 custom_emoji_keyword::table.on(custom_emoji_keyword::custom_emoji_id.eq(custom_emoji::id)),
48 .order(custom_emoji::category)
49 .then_order_by(custom_emoji::id)
51 custom_emoji::all_columns,
52 custom_emoji_keyword::all_columns.nullable(), // (or all the columns if you want)
54 .load::<CustomEmojiTuple>(conn)
57 Ok(CustomEmojiView::from_tuple_to_vec(emojis))
60 fn from_tuple_to_vec(items: Vec<CustomEmojiTuple>) -> Vec<Self> {
61 let mut result = Vec::new();
62 let mut hash: HashMap<CustomEmojiId, Vec<CustomEmojiKeyword>> = HashMap::new();
64 let emoji_id: CustomEmojiId = item.0.id;
65 if let std::collections::hash_map::Entry::Vacant(e) = hash.entry(emoji_id) {
67 result.push(CustomEmojiView {
68 custom_emoji: item.0.clone(),
72 if let Some(item_keyword) = &item.1 {
73 if let Some(keywords) = hash.get_mut(&emoji_id) {
74 keywords.push(item_keyword.clone())
78 for emoji in &mut result {
79 if let Some(keywords) = hash.get_mut(&emoji.custom_emoji.id) {
80 emoji.keywords = keywords.clone();