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