]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/language.rs
Various pedantic clippy fixes (#2568)
[lemmy.git] / crates / db_schema / src / impls / language.rs
1 use crate::{
2   diesel::ExpressionMethods,
3   newtypes::LanguageId,
4   schema::language::dsl::{code, id, language},
5   source::language::Language,
6   utils::{get_conn, DbPool},
7 };
8 use diesel::{result::Error, QueryDsl};
9 use diesel_async::{AsyncPgConnection, RunQueryDsl};
10
11 impl Language {
12   pub async fn read_all(pool: &DbPool) -> Result<Vec<Language>, Error> {
13     let conn = &mut get_conn(pool).await?;
14     Self::read_all_conn(conn).await
15   }
16
17   pub async fn read_all_conn(conn: &mut AsyncPgConnection) -> Result<Vec<Language>, Error> {
18     language.load::<Self>(conn).await
19   }
20
21   pub async fn read_from_id(pool: &DbPool, id_: LanguageId) -> Result<Language, Error> {
22     let conn = &mut get_conn(pool).await?;
23     language.filter(id.eq(id_)).first::<Self>(conn).await
24   }
25
26   pub async fn read_id_from_code(pool: &DbPool, code_: &str) -> Result<LanguageId, Error> {
27     let conn = &mut get_conn(pool).await?;
28     Ok(
29       language
30         .filter(code.eq(code_))
31         .first::<Self>(conn)
32         .await?
33         .id,
34     )
35   }
36
37   pub async fn read_id_from_code_opt(
38     pool: &DbPool,
39     code_: Option<&str>,
40   ) -> Result<Option<LanguageId>, Error> {
41     if let Some(code_) = code_ {
42       Ok(Some(Language::read_id_from_code(pool, code_).await?))
43     } else {
44       Ok(None)
45     }
46   }
47 }
48
49 #[cfg(test)]
50 mod tests {
51   use crate::{source::language::Language, utils::build_db_pool_for_tests};
52   use serial_test::serial;
53
54   #[tokio::test]
55   #[serial]
56   async fn test_languages() {
57     let pool = &build_db_pool_for_tests().await;
58
59     let all = Language::read_all(pool).await.unwrap();
60
61     assert_eq!(184, all.len());
62     assert_eq!("ak", all[5].code);
63     assert_eq!("lv", all[99].code);
64     assert_eq!("yi", all[179].code);
65   }
66 }