]> Untitled Git - lemmy.git/blob - crates/db_schema/src/lib.rs
Use URL type in most outstanding struct fields (#1468)
[lemmy.git] / crates / db_schema / src / lib.rs
1 #[macro_use]
2 extern crate diesel;
3
4 use chrono::NaiveDateTime;
5 use diesel::{
6   backend::Backend,
7   deserialize::FromSql,
8   serialize::{Output, ToSql},
9   sql_types::Text,
10 };
11 use serde::{Deserialize, Serialize};
12 use std::{
13   fmt::{Display, Formatter},
14   io::Write,
15 };
16 use url::Url;
17
18 pub mod schema;
19 pub mod source;
20
21 #[repr(transparent)]
22 #[derive(Clone, PartialEq, Serialize, Deserialize, Debug, AsExpression, FromSqlRow)]
23 #[sql_type = "Text"]
24 pub struct DbUrl(Url);
25
26 impl<DB: Backend> ToSql<Text, DB> for DbUrl
27 where
28   String: ToSql<Text, DB>,
29 {
30   fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> diesel::serialize::Result {
31     self.0.to_string().to_sql(out)
32   }
33 }
34
35 impl<DB: Backend> FromSql<Text, DB> for DbUrl
36 where
37   String: FromSql<Text, DB>,
38 {
39   fn from_sql(bytes: Option<&DB::RawValue>) -> diesel::deserialize::Result<Self> {
40     let str = String::from_sql(bytes)?;
41     Ok(DbUrl(Url::parse(&str)?))
42   }
43 }
44
45 impl DbUrl {
46   pub fn into_inner(self) -> Url {
47     self.0
48   }
49 }
50
51 impl Display for DbUrl {
52   fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
53     self.to_owned().into_inner().fmt(f)
54   }
55 }
56
57 impl From<DbUrl> for Url {
58   fn from(url: DbUrl) -> Self {
59     url.0
60   }
61 }
62
63 impl From<Url> for DbUrl {
64   fn from(url: Url) -> Self {
65     DbUrl(url)
66   }
67 }
68
69 // TODO: can probably move this back to lemmy_db_queries
70 pub fn naive_now() -> NaiveDateTime {
71   chrono::prelude::Utc::now().naive_utc()
72 }