1 use crate::{limit_and_offset, MaybeOptional};
2 use diesel::{pg::Pg, result::Error, *};
3 use serde::{Deserialize, Serialize};
5 // The faked schema since diesel doesn't do views
7 private_message_view (id) {
14 published -> Timestamp,
15 updated -> Nullable<Timestamp>,
18 creator_name -> Varchar,
19 creator_avatar -> Nullable<Text>,
20 creator_actor_id -> Text,
21 creator_local -> Bool,
22 recipient_name -> Varchar,
23 recipient_avatar -> Nullable<Text>,
24 recipient_actor_id -> Text,
25 recipient_local -> Bool,
30 Queryable, Identifiable, PartialEq, Debug, Serialize, Deserialize, QueryableByName, Clone,
32 #[table_name = "private_message_view"]
33 pub struct PrivateMessageView {
36 pub recipient_id: i32,
40 pub published: chrono::NaiveDateTime,
41 pub updated: Option<chrono::NaiveDateTime>,
44 pub creator_name: String,
45 pub creator_avatar: Option<String>,
46 pub creator_actor_id: String,
47 pub creator_local: bool,
48 pub recipient_name: String,
49 pub recipient_avatar: Option<String>,
50 pub recipient_actor_id: String,
51 pub recipient_local: bool,
54 pub struct PrivateMessageQueryBuilder<'a> {
55 conn: &'a PgConnection,
56 query: super::private_message_view::private_message_view::BoxedQuery<'a, Pg>,
57 for_recipient_id: i32,
63 impl<'a> PrivateMessageQueryBuilder<'a> {
64 pub fn create(conn: &'a PgConnection, for_recipient_id: i32) -> Self {
65 use super::private_message_view::private_message_view::dsl::*;
67 let query = private_message_view.into_boxed();
69 PrivateMessageQueryBuilder {
79 pub fn unread_only(mut self, unread_only: bool) -> Self {
80 self.unread_only = unread_only;
84 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
85 self.page = page.get_optional();
89 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
90 self.limit = limit.get_optional();
94 pub fn list(self) -> Result<Vec<PrivateMessageView>, Error> {
95 use super::private_message_view::private_message_view::dsl::*;
97 let mut query = self.query.filter(deleted.eq(false));
99 // If its unread, I only want the ones to me
100 if self.unread_only {
102 .filter(read.eq(false))
103 .filter(recipient_id.eq(self.for_recipient_id));
105 // Otherwise, I want the ALL view to show both sent and received
107 query = query.filter(
109 .eq(self.for_recipient_id)
110 .or(creator_id.eq(self.for_recipient_id)),
114 let (limit, offset) = limit_and_offset(self.page, self.limit);
119 .order_by(published.desc())
120 .load::<PrivateMessageView>(self.conn)
124 impl PrivateMessageView {
125 pub fn read(conn: &PgConnection, from_private_message_id: i32) -> Result<Self, Error> {
126 use super::private_message_view::private_message_view::dsl::*;
128 let mut query = private_message_view.into_boxed();
131 .filter(id.eq(from_private_message_id))
132 .order_by(published.desc());
134 query.first::<Self>(conn)