database stuff, not including tests

This commit is contained in:
Dull Bananas 2024-09-01 11:00:58 -07:00
parent 101476df87
commit e8344a1aff
9 changed files with 614 additions and 1 deletions

View file

@ -91,6 +91,12 @@ pub struct PersonMentionId(i32);
/// The comment report id. /// The comment report id.
pub struct CommentReportId(i32); pub struct CommentReportId(i32);
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "full", derive(DieselNewType, TS))]
#[cfg_attr(feature = "full", ts(export))]
/// The community report id.
pub struct CommunityReportId(i32);
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Default)] #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "full", derive(DieselNewType, TS))] #[cfg_attr(feature = "full", derive(DieselNewType, TS))]
#[cfg_attr(feature = "full", ts(export))] #[cfg_attr(feature = "full", ts(export))]

View file

@ -251,6 +251,23 @@ diesel::table! {
} }
} }
diesel::table! {
community_report (id) {
id -> Int4,
creator_id -> Int4,
community_id -> Int4,
original_community_title -> Text,
original_community_description -> Text,
original_community_icon -> Text,
original_community_banner -> Text,
reason -> Text,
resolved -> Bool,
resolver_id -> Nullable<Int4>,
published -> Timestamptz,
updated -> Nullable<Timestamptz>,
}
}
diesel::table! { diesel::table! {
custom_emoji (id) { custom_emoji (id) {
id -> Int4, id -> Int4,
@ -974,6 +991,7 @@ diesel::joinable!(community_moderator -> community (community_id));
diesel::joinable!(community_moderator -> person (person_id)); diesel::joinable!(community_moderator -> person (person_id));
diesel::joinable!(community_person_ban -> community (community_id)); diesel::joinable!(community_person_ban -> community (community_id));
diesel::joinable!(community_person_ban -> person (person_id)); diesel::joinable!(community_person_ban -> person (person_id));
diesel::joinable!(community_report -> community (community_id));
diesel::joinable!(custom_emoji -> local_site (local_site_id)); diesel::joinable!(custom_emoji -> local_site (local_site_id));
diesel::joinable!(custom_emoji_keyword -> custom_emoji (custom_emoji_id)); diesel::joinable!(custom_emoji_keyword -> custom_emoji (custom_emoji_id));
diesel::joinable!(email_verification -> local_user (local_user_id)); diesel::joinable!(email_verification -> local_user (local_user_id));
@ -1057,6 +1075,7 @@ diesel::allow_tables_to_appear_in_same_query!(
community_language, community_language,
community_moderator, community_moderator,
community_person_ban, community_person_ban,
community_report,
custom_emoji, custom_emoji,
custom_emoji_keyword, custom_emoji_keyword,
email_verification, email_verification,

View file

@ -0,0 +1,50 @@
use crate::newtypes::{CommunityId, CommunityReportId, PersonId};
#[cfg(feature = "full")]
use crate::schema::community_report;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
#[cfg(feature = "full")]
use ts_rs::TS;
#[skip_serializing_none]
#[derive(PartialEq, Eq, Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(
feature = "full",
derive(Queryable, Selectable, Associations, Identifiable, TS)
)]
#[cfg_attr(
feature = "full",
diesel(belongs_to(crate::source::community::Community))
)]
#[cfg_attr(feature = "full", diesel(table_name = community_report))]
#[cfg_attr(feature = "full", diesel(check_for_backend(diesel::pg::Pg)))]
#[cfg_attr(feature = "full", ts(export))]
/// A comment report.
pub struct CommunityReport {
pub id: CommunityReportId,
pub creator_id: PersonId,
pub community_id: CommunityId,
pub original_community_title: String,
pub original_community_description: String,
pub original_community_icon: String,
pub original_community_banner: String,
pub reason: String,
pub resolved: bool,
pub resolver_id: Option<PersonId>,
pub published: DateTime<Utc>,
pub updated: Option<DateTime<Utc>>,
}
#[derive(Clone)]
#[cfg_attr(feature = "full", derive(Insertable, AsChangeset))]
#[cfg_attr(feature = "full", diesel(table_name = community_report))]
pub struct CommunityReportForm {
pub creator_id: PersonId,
pub community_id: CommunityId,
pub original_community_title: String,
pub original_community_description: String,
pub original_community_icon: String,
pub original_community_banner: String,
pub reason: String,
}

View file

@ -10,6 +10,7 @@ pub mod comment_reply;
pub mod comment_report; pub mod comment_report;
pub mod community; pub mod community;
pub mod community_block; pub mod community_block;
pub mod community_report;
pub mod custom_emoji; pub mod custom_emoji;
pub mod custom_emoji_keyword; pub mod custom_emoji_keyword;
pub mod email_verification; pub mod email_verification;

View file

@ -0,0 +1,493 @@
use crate::structs::{CommunityReportView, LocalUserView};
use diesel::{
dsl::not,
result::Error,
BoolExpressionMethods,
ExpressionMethods,
JoinOnDsl,
NullableExpressionMethods,
QueryDsl,
};
use diesel_async::RunQueryDsl;
use lemmy_db_schema::{
aliases,
newtypes::{CommunityId, CommunityReportId, PersonId},
schema::{community, community_aggregates, community_follower, community_report, person},
utils::{get_conn, limit_and_offset, DbConn, DbPool, ListFn, Queries, ReadFn},
};
fn queries<'a>() -> Queries<
impl ReadFn<'a, CommunityReportView, (CommunityReportId, PersonId)>,
impl ListFn<'a, CommunityReportView, (CommunityReportQuery, &'a LocalUserView)>,
> {
let all_joins = |my_person_id: PersonId| {
community_report::table
.inner_join(community::table)
.inner_join(
community_aggregates::table
.on(community_report::community_id.eq(community_aggregates::community_id)),
)
.inner_join(person::table.on(community_report::creator_id.eq(person::id)))
.left_join(
aliases::person2
.on(community_report::resolver_id.eq(aliases::person2.field(person::id).nullable())),
)
.left_join(
community_follower::table.on(
community_report::community_id
.eq(community_follower::community_id)
.and(community_follower::person_id.eq(my_person_id)),
),
)
.select((
community_report::all_columns,
community::all_columns,
person::all_columns,
community_aggregates::all_columns,
community_follower::pending.nullable(),
aliases::person2.fields(person::all_columns).nullable(),
))
.into_boxed()
};
let read = move |mut conn: DbConn<'a>,
(report_id, my_person_id): (CommunityReportId, PersonId)| async move {
all_joins(my_person_id)
.filter(community_report::id.eq(report_id))
.first(&mut conn)
.await
};
let list = move |mut conn: DbConn<'a>,
(options, user): (CommunityReportQuery, &'a LocalUserView)| async move {
let mut query = all_joins(user.person.id);
if let Some(community_id) = options.community_id {
query = query.filter(community_report::community_id.eq(community_id));
}
// If viewing all reports, order by newest, but if viewing unresolved only, show the oldest
// first (FIFO)
if options.unresolved_only {
query = query
.filter(not(community_report::resolved))
.order_by(community_report::published.asc());
} else {
query = query.order_by(community_report::published.desc());
}
let (limit, offset) = limit_and_offset(options.page, options.limit)?;
query
.limit(limit)
.offset(offset)
.load::<CommunityReportView>(&mut conn)
.await
};
Queries::new(read, list)
}
impl CommunityReportView {
/// returns the CommentReportView for the provided report_id
///
/// * `report_id` - the report id to obtain
pub async fn read(
pool: &mut DbPool<'_>,
report_id: CommunityReportId,
my_person_id: PersonId,
) -> Result<Option<Self>, Error> {
queries().read(pool, (report_id, my_person_id)).await
}
/// Returns the current unresolved community report count
pub async fn get_report_count(pool: &mut DbPool<'_>) -> Result<i64, Error> {
use diesel::dsl::count;
let conn = &mut get_conn(pool).await?;
let query = community_report::table
.filter(not(community_report::resolved))
.into_boxed();
query
.select(count(community_report::id))
.first::<i64>(conn)
.await
}
}
#[derive(Default)]
pub struct CommunityReportQuery {
pub community_id: Option<CommunityId>,
pub page: Option<i64>,
pub limit: Option<i64>,
pub unresolved_only: bool,
}
impl CommunityReportQuery {
pub async fn list(
self,
pool: &mut DbPool<'_>,
user: &LocalUserView,
) -> Result<Vec<CommunityReportView>, Error> {
queries().list(pool, (self, user)).await
}
}
/*#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::indexing_slicing)]
mod tests {
use crate::{
comment_report_view::{CommentReportQuery, CommentReportView},
structs::LocalUserView,
};
use lemmy_db_schema::{
aggregates::structs::CommentAggregates,
source::{
comment::{Comment, CommentInsertForm},
comment_report::{CommentReport, CommentReportForm},
community::{Community, CommunityInsertForm, CommunityModerator, CommunityModeratorForm},
instance::Instance,
local_user::{LocalUser, LocalUserInsertForm},
local_user_vote_display_mode::LocalUserVoteDisplayMode,
person::{Person, PersonInsertForm},
post::{Post, PostInsertForm},
},
traits::{Crud, Joinable, Reportable},
utils::{build_db_pool_for_tests, RANK_DEFAULT},
CommunityVisibility,
SubscribedType,
};
use pretty_assertions::assert_eq;
use serial_test::serial;
#[tokio::test]
#[serial]
async fn test_crud() {
let pool = &build_db_pool_for_tests().await;
let pool = &mut pool.into();
let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
.await
.unwrap();
let new_person = PersonInsertForm::test_form(inserted_instance.id, "timmy_crv");
let inserted_timmy = Person::create(pool, &new_person).await.unwrap();
let new_local_user = LocalUserInsertForm::test_form(inserted_timmy.id);
let timmy_local_user = LocalUser::create(pool, &new_local_user, vec![])
.await
.unwrap();
let timmy_view = LocalUserView {
local_user: timmy_local_user,
local_user_vote_display_mode: LocalUserVoteDisplayMode::default(),
person: inserted_timmy.clone(),
counts: Default::default(),
};
let new_person_2 = PersonInsertForm::test_form(inserted_instance.id, "sara_crv");
let inserted_sara = Person::create(pool, &new_person_2).await.unwrap();
// Add a third person, since new ppl can only report something once.
let new_person_3 = PersonInsertForm::test_form(inserted_instance.id, "jessica_crv");
let inserted_jessica = Person::create(pool, &new_person_3).await.unwrap();
let new_community = CommunityInsertForm::builder()
.name("test community crv".to_string())
.title("nada".to_owned())
.public_key("pubkey".to_string())
.instance_id(inserted_instance.id)
.build();
let inserted_community = Community::create(pool, &new_community).await.unwrap();
// Make timmy a mod
let timmy_moderator_form = CommunityModeratorForm {
community_id: inserted_community.id,
person_id: inserted_timmy.id,
};
let _inserted_moderator = CommunityModerator::join(pool, &timmy_moderator_form)
.await
.unwrap();
let new_post = PostInsertForm::builder()
.name("A test post crv".into())
.creator_id(inserted_timmy.id)
.community_id(inserted_community.id)
.build();
let inserted_post = Post::create(pool, &new_post).await.unwrap();
let comment_form = CommentInsertForm::builder()
.content("A test comment 32".into())
.creator_id(inserted_timmy.id)
.post_id(inserted_post.id)
.build();
let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap();
// sara reports
let sara_report_form = CommentReportForm {
creator_id: inserted_sara.id,
comment_id: inserted_comment.id,
original_comment_text: "this was it at time of creation".into(),
reason: "from sara".into(),
};
let inserted_sara_report = CommentReport::report(pool, &sara_report_form)
.await
.unwrap();
// jessica reports
let jessica_report_form = CommentReportForm {
creator_id: inserted_jessica.id,
comment_id: inserted_comment.id,
original_comment_text: "this was it at time of creation".into(),
reason: "from jessica".into(),
};
let inserted_jessica_report = CommentReport::report(pool, &jessica_report_form)
.await
.unwrap();
let agg = CommentAggregates::read(pool, inserted_comment.id)
.await
.unwrap()
.unwrap();
let read_jessica_report_view =
CommentReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
.await
.unwrap()
.unwrap();
let expected_jessica_report_view = CommentReportView {
comment_report: inserted_jessica_report.clone(),
comment: inserted_comment.clone(),
post: inserted_post,
creator_is_moderator: true,
creator_is_admin: false,
creator_blocked: false,
subscribed: SubscribedType::NotSubscribed,
saved: false,
community: Community {
id: inserted_community.id,
name: inserted_community.name,
icon: None,
removed: false,
deleted: false,
nsfw: false,
actor_id: inserted_community.actor_id.clone(),
local: true,
title: inserted_community.title,
description: None,
updated: None,
banner: None,
hidden: false,
posting_restricted_to_mods: false,
published: inserted_community.published,
private_key: inserted_community.private_key,
public_key: inserted_community.public_key,
last_refreshed_at: inserted_community.last_refreshed_at,
followers_url: inserted_community.followers_url,
inbox_url: inserted_community.inbox_url,
shared_inbox_url: inserted_community.shared_inbox_url,
moderators_url: inserted_community.moderators_url,
featured_url: inserted_community.featured_url,
instance_id: inserted_instance.id,
visibility: CommunityVisibility::Public,
},
creator: Person {
id: inserted_jessica.id,
name: inserted_jessica.name,
display_name: None,
published: inserted_jessica.published,
avatar: None,
actor_id: inserted_jessica.actor_id.clone(),
local: true,
banned: false,
deleted: false,
bot_account: false,
bio: None,
banner: None,
updated: None,
inbox_url: inserted_jessica.inbox_url.clone(),
shared_inbox_url: None,
matrix_user_id: None,
ban_expires: None,
instance_id: inserted_instance.id,
private_key: inserted_jessica.private_key,
public_key: inserted_jessica.public_key,
last_refreshed_at: inserted_jessica.last_refreshed_at,
},
comment_creator: Person {
id: inserted_timmy.id,
name: inserted_timmy.name.clone(),
display_name: None,
published: inserted_timmy.published,
avatar: None,
actor_id: inserted_timmy.actor_id.clone(),
local: true,
banned: false,
deleted: false,
bot_account: false,
bio: None,
banner: None,
updated: None,
inbox_url: inserted_timmy.inbox_url.clone(),
shared_inbox_url: None,
matrix_user_id: None,
ban_expires: None,
instance_id: inserted_instance.id,
private_key: inserted_timmy.private_key.clone(),
public_key: inserted_timmy.public_key.clone(),
last_refreshed_at: inserted_timmy.last_refreshed_at,
},
creator_banned_from_community: false,
counts: CommentAggregates {
comment_id: inserted_comment.id,
score: 0,
upvotes: 0,
downvotes: 0,
published: agg.published,
child_count: 0,
hot_rank: RANK_DEFAULT,
controversy_rank: 0.0,
},
my_vote: None,
resolver: None,
};
assert_eq!(read_jessica_report_view, expected_jessica_report_view);
let mut expected_sara_report_view = expected_jessica_report_view.clone();
expected_sara_report_view.comment_report = inserted_sara_report;
expected_sara_report_view.creator = Person {
id: inserted_sara.id,
name: inserted_sara.name,
display_name: None,
published: inserted_sara.published,
avatar: None,
actor_id: inserted_sara.actor_id.clone(),
local: true,
banned: false,
deleted: false,
bot_account: false,
bio: None,
banner: None,
updated: None,
inbox_url: inserted_sara.inbox_url.clone(),
shared_inbox_url: None,
matrix_user_id: None,
ban_expires: None,
instance_id: inserted_instance.id,
private_key: inserted_sara.private_key,
public_key: inserted_sara.public_key,
last_refreshed_at: inserted_sara.last_refreshed_at,
};
// Do a batch read of timmys reports
let reports = CommentReportQuery::default()
.list(pool, &timmy_view)
.await
.unwrap();
assert_eq!(
reports,
[
expected_jessica_report_view.clone(),
expected_sara_report_view.clone(),
]
);
// Make sure the counts are correct
let report_count = CommentReportView::get_report_count(pool, inserted_timmy.id, false, None)
.await
.unwrap();
assert_eq!(2, report_count);
// Try to resolve the report
CommentReport::resolve(pool, inserted_jessica_report.id, inserted_timmy.id)
.await
.unwrap();
let read_jessica_report_view_after_resolve =
CommentReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id)
.await
.unwrap()
.unwrap();
let mut expected_jessica_report_view_after_resolve = expected_jessica_report_view;
expected_jessica_report_view_after_resolve
.comment_report
.resolved = true;
expected_jessica_report_view_after_resolve
.comment_report
.resolver_id = Some(inserted_timmy.id);
expected_jessica_report_view_after_resolve
.comment_report
.updated = read_jessica_report_view_after_resolve
.comment_report
.updated;
expected_jessica_report_view_after_resolve.resolver = Some(Person {
id: inserted_timmy.id,
name: inserted_timmy.name.clone(),
display_name: None,
published: inserted_timmy.published,
avatar: None,
actor_id: inserted_timmy.actor_id.clone(),
local: true,
banned: false,
deleted: false,
bot_account: false,
bio: None,
banner: None,
updated: None,
inbox_url: inserted_timmy.inbox_url.clone(),
private_key: inserted_timmy.private_key.clone(),
public_key: inserted_timmy.public_key.clone(),
last_refreshed_at: inserted_timmy.last_refreshed_at,
shared_inbox_url: None,
matrix_user_id: None,
ban_expires: None,
instance_id: inserted_instance.id,
});
assert_eq!(
read_jessica_report_view_after_resolve,
expected_jessica_report_view_after_resolve
);
// Do a batch read of timmys reports
// It should only show saras, which is unresolved
let reports_after_resolve = CommentReportQuery {
unresolved_only: (true),
..Default::default()
}
.list(pool, &timmy_view)
.await
.unwrap();
assert_eq!(reports_after_resolve[0], expected_sara_report_view);
assert_eq!(reports_after_resolve.len(), 1);
// Make sure the counts are correct
let report_count_after_resolved =
CommentReportView::get_report_count(pool, inserted_timmy.id, false, None)
.await
.unwrap();
assert_eq!(1, report_count_after_resolved);
Person::delete(pool, inserted_timmy.id).await.unwrap();
Person::delete(pool, inserted_sara.id).await.unwrap();
Person::delete(pool, inserted_jessica.id).await.unwrap();
Community::delete(pool, inserted_community.id)
.await
.unwrap();
Instance::delete(pool, inserted_instance.id).await.unwrap();
}
}*/

View file

@ -6,6 +6,8 @@ pub mod comment_report_view;
#[cfg(feature = "full")] #[cfg(feature = "full")]
pub mod comment_view; pub mod comment_view;
#[cfg(feature = "full")] #[cfg(feature = "full")]
pub mod community_report_view;
#[cfg(feature = "full")]
pub mod custom_emoji_view; pub mod custom_emoji_view;
#[cfg(feature = "full")] #[cfg(feature = "full")]
pub mod local_image_view; pub mod local_image_view;

View file

@ -1,11 +1,18 @@
#[cfg(feature = "full")] #[cfg(feature = "full")]
use diesel::Queryable; use diesel::Queryable;
use lemmy_db_schema::{ use lemmy_db_schema::{
aggregates::structs::{CommentAggregates, PersonAggregates, PostAggregates, SiteAggregates}, aggregates::structs::{
CommentAggregates,
CommunityAggregates,
PersonAggregates,
PostAggregates,
SiteAggregates,
},
source::{ source::{
comment::Comment, comment::Comment,
comment_report::CommentReport, comment_report::CommentReport,
community::Community, community::Community,
community_report::CommunityReport,
custom_emoji::CustomEmoji, custom_emoji::CustomEmoji,
custom_emoji_keyword::CustomEmojiKeyword, custom_emoji_keyword::CustomEmojiKeyword,
images::{ImageDetails, LocalImage}, images::{ImageDetails, LocalImage},
@ -74,6 +81,21 @@ pub struct CommentView {
pub my_vote: Option<i16>, pub my_vote: Option<i16>,
} }
#[skip_serializing_none]
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "full", derive(TS, Queryable))]
#[cfg_attr(feature = "full", diesel(check_for_backend(diesel::pg::Pg)))]
#[cfg_attr(feature = "full", ts(export))]
/// A community report view.
pub struct CommunityReportView {
pub community_report: CommunityReport,
pub community: Community,
pub creator: Person,
pub counts: CommunityAggregates,
pub subscribed: SubscribedType,
pub resolver: Option<Person>,
}
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "full", derive(TS, Queryable))] #[cfg_attr(feature = "full", derive(TS, Queryable))]
#[cfg_attr(feature = "full", diesel(check_for_backend(diesel::pg::Pg)))] #[cfg_attr(feature = "full", diesel(check_for_backend(diesel::pg::Pg)))]

View file

@ -0,0 +1,2 @@
DROP TABLE community_report CASCADE;

View file

@ -0,0 +1,18 @@
CREATE TABLE community_report (
id serial PRIMARY KEY,
creator_id int REFERENCES person ON UPDATE CASCADE ON DELETE CASCADE NOT NULL,
community_id int REFERENCES community ON UPDATE CASCADE ON DELETE CASCADE NOT NULL,
original_community_title text NOT NULL,
original_community_description text NOT NULL,
original_community_icon text NOT NULL,
original_community_banner text NOT NULL,
reason text NOT NULL,
resolved bool NOT NULL DEFAULT FALSE,
resolver_id int REFERENCES person ON UPDATE CASCADE ON DELETE CASCADE,
published timestamptz NOT NULL DEFAULT now(),
updated timestamptz NULL,
UNIQUE (community_id, creator_id)
);
CREATE INDEX idx_community_report_published ON community_report (published DESC);