From 743620eb6a54baa45ccfbdcdbbe3b49bb3fd45f7 Mon Sep 17 00:00:00 2001 From: Bat Date: Thu, 27 Sep 2018 22:06:40 +0100 Subject: [PATCH] Fix the SQlite build --- plume-models/Cargo.toml | 1 - plume-models/src/blog_authors.rs | 2 +- plume-models/src/blogs.rs | 17 ++++++------ plume-models/src/comments.rs | 19 ++++++------- plume-models/src/db_conn.rs | 11 ++++---- plume-models/src/follows.rs | 10 +++---- plume-models/src/instance.rs | 15 ++++++----- plume-models/src/lib.rs | 45 ++++++++++++++++++++----------- plume-models/src/likes.rs | 4 +-- plume-models/src/medias.rs | 2 +- plume-models/src/mentions.rs | 6 ++--- plume-models/src/notifications.rs | 7 ++--- plume-models/src/post_authors.rs | 2 +- plume-models/src/posts.rs | 35 +++++++++++++----------- plume-models/src/reshares.rs | 17 ++++++------ plume-models/src/safe_string.rs | 7 +++++ plume-models/src/users.rs | 36 ++++++++++++------------- src/inbox.rs | 4 +-- src/routes/mod.rs | 5 ++-- src/setup.rs | 11 ++++---- 20 files changed, 142 insertions(+), 114 deletions(-) diff --git a/plume-models/Cargo.toml b/plume-models/Cargo.toml index c05d7a89..fbbe332d 100644 --- a/plume-models/Cargo.toml +++ b/plume-models/Cargo.toml @@ -37,6 +37,5 @@ git = "https://github.com/SergioBenitez/Rocket" rev = "55459db7732b9a240826a5c120c650f87e3372ce" [features] -default = ["postgres"] postgres = ["diesel/postgres"] sqlite = ["diesel/sqlite"] diff --git a/plume-models/src/blog_authors.rs b/plume-models/src/blog_authors.rs index 95f8a4d2..65e04969 100644 --- a/plume-models/src/blog_authors.rs +++ b/plume-models/src/blog_authors.rs @@ -2,7 +2,7 @@ use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods}; use schema::blog_authors; -#[derive(Queryable, Identifiable)] +#[derive(Clone, Queryable, Identifiable)] pub struct BlogAuthor { pub id: i32, pub blog_id: i32, diff --git a/plume-models/src/blogs.rs b/plume-models/src/blogs.rs index 2005bf09..741cc7ef 100644 --- a/plume-models/src/blogs.rs +++ b/plume-models/src/blogs.rs @@ -1,4 +1,5 @@ use activitypub::{Actor, Object, CustomObject, actor::Group, collection::OrderedCollection}; +use chrono::NaiveDateTime; use reqwest::{ Client, header::{Accept, qitem}, @@ -6,7 +7,7 @@ use reqwest::{ }; use serde_json; use url::Url; -use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, dsl::any}; +use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods}; use openssl::{ hash::MessageDigest, pkey::{PKey, Private}, @@ -15,7 +16,7 @@ use openssl::{ }; use webfinger::*; -use {BASE_URL, USE_HTTPS, Connection, SqlDateTime}; +use {BASE_URL, USE_HTTPS, Connection}; use plume_common::activity_pub::{ ap_accept_header, ApSignature, ActivityStream, Id, IntoId, PublicKey, inbox::WithInbox, @@ -37,7 +38,7 @@ pub struct Blog { pub outbox_url: String, pub inbox_url: String, pub instance_id: i32, - pub creation_date: SqlDateTime, + pub creation_date: NaiveDateTime, pub ap_url: String, pub private_key: Option, pub public_key: String @@ -73,7 +74,7 @@ impl Blog { use schema::blog_authors; use schema::users; let authors_ids = blog_authors::table.filter(blog_authors::blog_id.eq(self.id)).select(blog_authors::author_id); - users::table.filter(users::id.eq(any(authors_ids))) + users::table.filter(users::id.eq_any(authors_ids)) .load::(conn) .expect("Couldn't load authors of a blog") } @@ -81,7 +82,7 @@ impl Blog { pub fn find_for_author(conn: &Connection, author_id: i32) -> Vec { use schema::blog_authors; let author_ids = blog_authors::table.filter(blog_authors::author_id.eq(author_id)).select(blog_authors::blog_id); - blogs::table.filter(blogs::id.eq(any(author_ids))) + blogs::table.filter(blogs::id.eq_any(author_ids)) .load::(conn) .expect("Couldn't load blogs ") } @@ -189,19 +190,19 @@ impl Blog { if self.outbox_url.len() == 0 { diesel::update(self) .set(blogs::outbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "outbox"))) - .get_result::(conn).expect("Couldn't update outbox URL"); + .execute(conn).expect("Couldn't update outbox URL"); } if self.inbox_url.len() == 0 { diesel::update(self) .set(blogs::inbox_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), "inbox"))) - .get_result::(conn).expect("Couldn't update inbox URL"); + .execute(conn).expect("Couldn't update inbox URL"); } if self.ap_url.len() == 0 { diesel::update(self) .set(blogs::ap_url.eq(instance.compute_box(BLOG_PREFIX, self.actor_id.clone(), ""))) - .get_result::(conn).expect("Couldn't update AP URL"); + .execute(conn).expect("Couldn't update AP URL"); } } diff --git a/plume-models/src/comments.rs b/plume-models/src/comments.rs index b35275e5..b7e2b756 100644 --- a/plume-models/src/comments.rs +++ b/plume-models/src/comments.rs @@ -3,8 +3,8 @@ use activitypub::{ link, object::{Note} }; -use chrono; -use diesel::{self, PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, dsl::any}; +use chrono::{self, NaiveDateTime}; +use diesel::{self, RunQueryDsl, QueryDsl, ExpressionMethods}; use serde_json; use plume_common::activity_pub::{ @@ -12,7 +12,7 @@ use plume_common::activity_pub::{ inbox::{FromActivity, Notify} }; use plume_common::utils; -use {Connection, SqlDateTime}; +use Connection; use instance::Instance; use mentions::Mention; use notifications::*; @@ -28,7 +28,7 @@ pub struct Comment { pub in_response_to_id: Option, pub post_id: i32, pub author_id: i32, - pub creation_date: SqlDateTime, + pub creation_date: NaiveDateTime, pub ap_url: Option, pub sensitive: bool, pub spoiler_text: String @@ -63,7 +63,7 @@ impl Comment { pub fn count_local(conn: &Connection) -> usize { use schema::users; let local_authors = users::table.filter(users::instance_id.eq(Instance::local_id(conn))).select(users::id); - comments::table.filter(comments::author_id.eq(any(local_authors))) + comments::table.filter(comments::author_id.eq_any(local_authors)) .load::(conn) .expect("Couldn't load local comments") .len() @@ -87,8 +87,9 @@ impl Comment { if self.ap_url.is_none() { diesel::update(self) .set(comments::ap_url.eq(self.compute_id(conn))) - .get_result(conn) - .expect("Failed to update comment AP URL") + .execute(conn) + .expect("Failed to update comment AP URL"); + Comment::get(conn, self.id).expect("Couldn't get the updated comment") } else { self.clone() } @@ -134,7 +135,7 @@ impl Comment { } } -impl FromActivity for Comment { +impl FromActivity for Comment { fn from_activity(conn: &Connection, note: Note, actor: Id) -> Comment { let previous_url = note.object_props.in_reply_to.clone().unwrap().as_str().unwrap().to_string(); let previous_comment = Comment::find_by_ap_url(conn, previous_url.clone()); @@ -168,7 +169,7 @@ impl FromActivity for Comment { } } -impl Notify for Comment { +impl Notify for Comment { fn notify(&self, conn: &Connection) { for author in self.get_post(conn).get_authors(conn) { Notification::insert(conn, NewNotification { diff --git a/plume-models/src/db_conn.rs b/plume-models/src/db_conn.rs index 557100d6..eef62825 100644 --- a/plume-models/src/db_conn.rs +++ b/plume-models/src/db_conn.rs @@ -1,16 +1,17 @@ use diesel::{ - pg::PgConnection, r2d2::{ConnectionManager, Pool, PooledConnection} }; use rocket::{Request, State, Outcome, http::Status, request::{self, FromRequest}}; use std::ops::Deref; -pub type PgPool = Pool>; +use Connection; + +pub type DbPool = Pool>; // From rocket documentation // Connection request guard type: a wrapper around an r2d2 pooled connection. -pub struct DbConn(pub PooledConnection>); +pub struct DbConn(pub PooledConnection>); /// Attempts to retrieve a single connection from the managed database pool. If /// no pool is currently managed, fails with an `InternalServerError` status. If @@ -19,7 +20,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for DbConn { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome { - let pool = request.guard::>()?; + let pool = request.guard::>()?; match pool.get() { Ok(conn) => Outcome::Success(DbConn(conn)), Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())) @@ -29,7 +30,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for DbConn { // For the convenience of using an &DbConn as an &Connection. impl Deref for DbConn { - type Target = PgConnection; + type Target = Connection; fn deref(&self) -> &Self::Target { &self.0 diff --git a/plume-models/src/follows.rs b/plume-models/src/follows.rs index 311d87d9..81606c02 100644 --- a/plume-models/src/follows.rs +++ b/plume-models/src/follows.rs @@ -1,5 +1,5 @@ use activitypub::{Actor, activity::{Accept, Follow as FollowAct, Undo}, actor::Person}; -use diesel::{self, PgConnection, ExpressionMethods, QueryDsl, RunQueryDsl}; +use diesel::{self, ExpressionMethods, QueryDsl, RunQueryDsl}; use plume_common::activity_pub::{broadcast, Id, IntoId, inbox::{FromActivity, Notify, WithInbox, Deletable}, sign::Signer}; use Connection; @@ -8,7 +8,7 @@ use notifications::*; use users::User; use schema::follows; -#[derive(Queryable, Identifiable, Associations)] +#[derive(Clone, Queryable, Identifiable, Associations)] #[belongs_to(User, foreign_key = "following_id")] pub struct Follow { pub id: i32, @@ -80,7 +80,7 @@ impl Follow { } } -impl FromActivity for Follow { +impl FromActivity for Follow { fn from_activity(conn: &Connection, follow: FollowAct, _actor: Id) -> Follow { let from_id = follow.follow_props.actor_link::().map(|l| l.into()) .unwrap_or_else(|_| follow.follow_props.actor_object::().expect("No actor object (nor ID) on Follow").object_props.id_string().expect("No ID on actor on Follow")); @@ -95,7 +95,7 @@ impl FromActivity for Follow { } } -impl Notify for Follow { +impl Notify for Follow { fn notify(&self, conn: &Connection) { Notification::insert(conn, NewNotification { kind: notification_kind::FOLLOW.to_string(), @@ -105,7 +105,7 @@ impl Notify for Follow { } } -impl Deletable for Follow { +impl Deletable for Follow { fn delete(&self, conn: &Connection) -> Undo { diesel::delete(self).execute(conn).expect("Coudn't delete follow"); diff --git a/plume-models/src/instance.rs b/plume-models/src/instance.rs index 9df7be91..ed072111 100644 --- a/plume-models/src/instance.rs +++ b/plume-models/src/instance.rs @@ -1,21 +1,22 @@ +use chrono::NaiveDateTime; use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods}; use std::iter::Iterator; use plume_common::utils::md_to_html; -use {Connection, SqlDateTime}; +use Connection; use safe_string::SafeString; use ap_url; use users::User; use schema::{instances, users}; -#[derive(Identifiable, Queryable, Serialize)] +#[derive(Clone, Identifiable, Queryable, Serialize)] pub struct Instance { pub id: i32, pub public_domain: String, pub name: String, pub local: bool, pub blocked: bool, - pub creation_date: SqlDateTime, + pub creation_date: NaiveDateTime, pub open_registrations: bool, pub short_description: SafeString, pub long_description: SafeString, @@ -72,7 +73,7 @@ impl Instance { pub fn toggle_block(&self, conn: &Connection) { diesel::update(self) .set(instances::blocked.eq(!self.blocked)) - .get_result::(conn) + .execute(conn) .expect("Couldn't block/unblock instance"); } @@ -115,7 +116,7 @@ impl Instance { )) } - pub fn update(&self, conn: &Connection, name: String, open_registrations: bool, short_description: SafeString, long_description: SafeString) -> Instance { + pub fn update(&self, conn: &Connection, name: String, open_registrations: bool, short_description: SafeString, long_description: SafeString) { let (sd, _) = md_to_html(short_description.as_ref()); let (ld, _) = md_to_html(long_description.as_ref()); diesel::update(self) @@ -126,8 +127,8 @@ impl Instance { instances::long_description.eq(long_description), instances::short_description_html.eq(sd), instances::long_description_html.eq(ld) - )).get_result::(conn) - .expect("Couldn't update instance") + )).execute(conn) + .expect("Couldn't update instance"); } pub fn count(conn: &Connection) -> i64 { diff --git a/plume-models/src/lib.rs b/plume-models/src/lib.rs index 04f485e3..8a0a6c3d 100644 --- a/plume-models/src/lib.rs +++ b/plume-models/src/lib.rs @@ -26,6 +26,12 @@ extern crate webfinger; use std::env; +#[cfg(all(feature = "sqlite", not(feature = "postgres")))] +pub type Connection = diesel::SqliteConnection; + +#[cfg(all(not(feature = "sqlite"), feature = "postgres"))] +pub type Connection = diesel::PgConnection; + macro_rules! find_by { ($table:ident, $fn:ident, $($col:ident as $type:ident),+) => { /// Try to find a $table with a given $col @@ -66,11 +72,14 @@ macro_rules! get { macro_rules! insert { ($table:ident, $from:ident) => { + last!($table); + pub fn insert(conn: &crate::Connection, new: $from) -> Self { diesel::insert_into($table::table) .values(new) - .get_result(conn) - .expect("Error saving new $table") + .execute(conn) + .expect("Error saving new $table"); + Self::last(conn) } }; } @@ -80,8 +89,24 @@ macro_rules! update { pub fn update(&self, conn: &crate::Connection) -> Self { diesel::update(self) .set(self) - .get_result(conn) - .expect(concat!("Error updating ", stringify!($table))) + .execute(conn) + .expect(concat!("Error updating ", stringify!($table))); + Self::get(conn, self.id) + .expect(concat!(stringify!($table), " we just updated doesn't exist anymore???")) + } + }; +} + +macro_rules! last { + ($table:ident) => { + pub fn last(conn: &crate::Connection) -> Self { + $table::table.order_by($table::id.desc()) + .limit(1) + .load::(conn) + .expect(concat!("Error getting last ", stringify!($table))) + .iter().next() + .expect(concat!("No last ", stringify!($table))) + .clone() } }; } @@ -105,18 +130,6 @@ pub fn ap_url(url: String) -> String { format!("{}://{}", scheme, url) } -#[cfg(all(not(feature = "postgres"), feature = "sqlite"))] -pub type SqlDateTime = chrono::NaiveDateTime; - -#[cfg(all(not(feature = "postgres"), feature = "sqlite"))] -pub type Connection = diesel::SqliteConnection; - -#[cfg(all(not(feature = "sqlite"), feature = "postgres"))] -pub type SqlDateTime = chrono::NaiveDateTime; - -#[cfg(all(not(feature = "sqlite"), feature = "postgres"))] -pub type Connection = diesel::PgConnection; - pub mod admin; pub mod blog_authors; pub mod blogs; diff --git a/plume-models/src/likes.rs b/plume-models/src/likes.rs index 31f59542..a7617b9e 100644 --- a/plume-models/src/likes.rs +++ b/plume-models/src/likes.rs @@ -14,7 +14,7 @@ use posts::Post; use users::User; use schema::likes; -#[derive(Queryable, Identifiable)] +#[derive(Clone, Queryable, Identifiable)] pub struct Like { pub id: i32, pub user_id: i32, @@ -45,7 +45,7 @@ impl Like { User::get(conn, self.user_id).unwrap().ap_url, Post::get(conn, self.post_id).unwrap().ap_url ))) - .get_result::(conn).expect("Couldn't update AP URL"); + .execute(conn).expect("Couldn't update AP URL"); } } diff --git a/plume-models/src/medias.rs b/plume-models/src/medias.rs index 7785dc4c..01639b18 100644 --- a/plume-models/src/medias.rs +++ b/plume-models/src/medias.rs @@ -6,7 +6,7 @@ use {ap_url, Connection}; use instance::Instance; use schema::medias; -#[derive(Identifiable, Queryable, Serialize)] +#[derive(Clone, Identifiable, Queryable, Serialize)] pub struct Media { pub id: i32, pub file_path: String, diff --git a/plume-models/src/mentions.rs b/plume-models/src/mentions.rs index 524a1e96..b7328b9c 100644 --- a/plume-models/src/mentions.rs +++ b/plume-models/src/mentions.rs @@ -1,5 +1,5 @@ use activitypub::link; -use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods}; +use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods}; use plume_common::activity_pub::inbox::Notify; use Connection; @@ -9,7 +9,7 @@ use posts::Post; use users::User; use schema::mentions; -#[derive(Queryable, Identifiable, Serialize, Deserialize)] +#[derive(Clone, Queryable, Identifiable, Serialize, Deserialize)] pub struct Mention { pub id: i32, pub mentioned_id: i32, @@ -104,7 +104,7 @@ impl Mention { } } -impl Notify for Mention { +impl Notify for Mention { fn notify(&self, conn: &Connection) { self.get_mentioned(conn).map(|m| { Notification::insert(conn, NewNotification { diff --git a/plume-models/src/notifications.rs b/plume-models/src/notifications.rs index 6060bc7d..268096ff 100644 --- a/plume-models/src/notifications.rs +++ b/plume-models/src/notifications.rs @@ -1,7 +1,8 @@ +use chrono::NaiveDateTime; use diesel::{self, RunQueryDsl, QueryDsl, ExpressionMethods}; use serde_json; -use {Connection, SqlDateTime}; +use Connection; use comments::Comment; use follows::Follow; use likes::Like; @@ -19,11 +20,11 @@ pub mod notification_kind { pub const RESHARE: &'static str = "RESHARE"; } -#[derive(Queryable, Identifiable, Serialize)] +#[derive(Clone, Queryable, Identifiable, Serialize)] pub struct Notification { pub id: i32, pub user_id: i32, - pub creation_date: SqlDateTime, + pub creation_date: NaiveDateTime, pub kind: String, pub object_id: i32 } diff --git a/plume-models/src/post_authors.rs b/plume-models/src/post_authors.rs index 2024881a..56b11c65 100644 --- a/plume-models/src/post_authors.rs +++ b/plume-models/src/post_authors.rs @@ -4,7 +4,7 @@ use posts::Post; use users::User; use schema::post_authors; -#[derive(Queryable, Identifiable, Associations)] +#[derive(Clone, Queryable, Identifiable, Associations)] #[belongs_to(Post)] #[belongs_to(User, foreign_key = "author_id")] pub struct PostAuthor { diff --git a/plume-models/src/posts.rs b/plume-models/src/posts.rs index 56d26a42..b0d164c8 100644 --- a/plume-models/src/posts.rs +++ b/plume-models/src/posts.rs @@ -5,7 +5,7 @@ use activitypub::{ }; use canapi::{Error, Provider}; use chrono::{NaiveDateTime, TimeZone, Utc}; -use diesel::{self, RunQueryDsl, QueryDsl, ExpressionMethods, BelongingToDsl, dsl::any}; +use diesel::{self, RunQueryDsl, QueryDsl, ExpressionMethods, BelongingToDsl}; use heck::KebabCase; use serde_json; @@ -15,7 +15,7 @@ use plume_common::activity_pub::{ PUBLIC_VISIBILTY, Id, IntoId, inbox::{Deletable, FromActivity} }; -use {BASE_URL, ap_url, Connection, SqlDateTime}; +use {BASE_URL, ap_url, Connection}; use blogs::Blog; use instance::Instance; use likes::Like; @@ -36,7 +36,7 @@ pub struct Post { pub content: SafeString, pub published: bool, pub license: String, - pub creation_date: SqlDateTime, + pub creation_date: NaiveDateTime, pub ap_url: String, pub subtitle: String, pub source: String, @@ -116,31 +116,32 @@ impl Post { use schema::tags; let ids = tags::table.filter(tags::tag.eq(tag)).select(tags::post_id); - posts::table.filter(posts::id.eq(any(ids))) + posts::table.filter(posts::id.eq_any(ids)) .filter(posts::published.eq(true)) .order(posts::creation_date.desc()) .offset(min.into()) .limit((max - min).into()) - .get_results::(conn) + .load(conn) .expect("Error loading posts by tag") } pub fn count_for_tag(conn: &Connection, tag: String) -> i64 { use schema::tags; let ids = tags::table.filter(tags::tag.eq(tag)).select(tags::post_id); - posts::table.filter(posts::id.eq(any(ids))) + *posts::table.filter(posts::id.eq_any(ids)) .filter(posts::published.eq(true)) .count() - .get_result(conn) + .load(conn) .expect("Error counting posts by tag") + .iter().next().unwrap() } pub fn count_local(conn: &Connection) -> usize { use schema::post_authors; use schema::users; let local_authors = users::table.filter(users::instance_id.eq(Instance::local_id(conn))).select(users::id); - let local_posts_id = post_authors::table.filter(post_authors::author_id.eq(any(local_authors))).select(post_authors::post_id); - posts::table.filter(posts::id.eq(any(local_posts_id))) + let local_posts_id = post_authors::table.filter(post_authors::author_id.eq_any(local_authors)).select(post_authors::post_id); + posts::table.filter(posts::id.eq_any(local_posts_id)) .filter(posts::published.eq(true)) .load::(conn) .expect("Couldn't load local posts") @@ -163,7 +164,7 @@ impl Post { use schema::post_authors; let posts = PostAuthor::belonging_to(author).select(post_authors::post_id); - posts::table.filter(posts::id.eq(any(posts))) + posts::table.filter(posts::id.eq_any(posts)) .filter(posts::published.eq(true)) .order(posts::creation_date.desc()) .limit(limit) @@ -215,7 +216,7 @@ impl Post { posts::table.order(posts::creation_date.desc()) .filter(posts::published.eq(true)) - .filter(posts::blog_id.eq(any(blog_ids))) + .filter(posts::blog_id.eq_any(blog_ids)) .offset(min.into()) .limit((max - min).into()) .load::(conn) @@ -225,12 +226,13 @@ impl Post { /// Give a page of customized user feed, based on a list of followed users pub fn user_feed_page(conn: &Connection, followed: Vec, (min, max): (i32, i32)) -> Vec { use schema::post_authors; - let post_ids = post_authors::table.filter(post_authors::author_id.eq(any(followed))) + let post_ids = post_authors::table + .filter(post_authors::author_id.eq_any(followed)) .select(post_authors::post_id); posts::table.order(posts::creation_date.desc()) .filter(posts::published.eq(true)) - .filter(posts::id.eq(any(post_ids))) + .filter(posts::id.eq_any(post_ids)) .offset(min.into()) .limit((max - min).into()) .load::(conn) @@ -243,7 +245,7 @@ impl Post { let posts = PostAuthor::belonging_to(author).select(post_authors::post_id); posts::table.order(posts::creation_date.desc()) .filter(posts::published.eq(false)) - .filter(posts::id.eq(any(posts))) + .filter(posts::id.eq_any(posts)) .load::(conn) .expect("Error listing drafts") } @@ -252,7 +254,7 @@ impl Post { use schema::users; use schema::post_authors; let author_list = PostAuthor::belonging_to(self).select(post_authors::author_id); - users::table.filter(users::id.eq(any(author_list))).load::(conn).unwrap() + users::table.filter(users::id.eq_any(author_list)).load::(conn).unwrap() } pub fn get_blog(&self, conn: &Connection) -> Blog { @@ -282,7 +284,8 @@ impl Post { if self.ap_url.len() == 0 { diesel::update(self) .set(posts::ap_url.eq(self.compute_id(conn))) - .get_result::(conn).expect("Couldn't update AP URL") + .execute(conn).expect("Couldn't update AP URL"); + Post::get(conn, self.id).unwrap() } else { self.clone() } diff --git a/plume-models/src/reshares.rs b/plume-models/src/reshares.rs index bb3fdbf6..db04bcc9 100644 --- a/plume-models/src/reshares.rs +++ b/plume-models/src/reshares.rs @@ -1,20 +1,21 @@ use activitypub::activity::{Announce, Undo}; -use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods}; +use chrono::NaiveDateTime; +use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods}; use plume_common::activity_pub::{Id, IntoId, inbox::{FromActivity, Notify, Deletable}, PUBLIC_VISIBILTY}; -use {Connection, SqlDateTime}; +use Connection; use notifications::*; use posts::Post; use users::User; use schema::reshares; -#[derive(Serialize, Deserialize, Queryable, Identifiable)] +#[derive(Clone, Serialize, Deserialize, Queryable, Identifiable)] pub struct Reshare { pub id: i32, pub user_id: i32, pub post_id: i32, pub ap_url: String, - pub creation_date: SqlDateTime + pub creation_date: NaiveDateTime } #[derive(Insertable)] @@ -39,7 +40,7 @@ impl Reshare { User::get(conn, self.user_id).unwrap().ap_url, Post::get(conn, self.post_id).unwrap().ap_url ))) - .get_result::(conn).expect("Couldn't update AP URL"); + .execute(conn).expect("Couldn't update AP URL"); } } @@ -71,7 +72,7 @@ impl Reshare { } } -impl FromActivity for Reshare { +impl FromActivity for Reshare { fn from_activity(conn: &Connection, announce: Announce, _actor: Id) -> Reshare { let user = User::from_url(conn, announce.announce_props.actor_link::().expect("Reshare::from_activity: actor error").into()); let post = Post::find_by_ap_url(conn, announce.announce_props.object_link::().expect("Reshare::from_activity: object error").into()); @@ -85,7 +86,7 @@ impl FromActivity for Reshare { } } -impl Notify for Reshare { +impl Notify for Reshare { fn notify(&self, conn: &Connection) { let post = self.get_post(conn).unwrap(); for author in post.get_authors(conn) { @@ -98,7 +99,7 @@ impl Notify for Reshare { } } -impl Deletable for Reshare { +impl Deletable for Reshare { fn delete(&self, conn: &Connection) -> Undo { diesel::delete(self).execute(conn).unwrap(); diff --git a/plume-models/src/safe_string.rs b/plume-models/src/safe_string.rs index 767e4bc6..ce813d45 100644 --- a/plume-models/src/safe_string.rs +++ b/plume-models/src/safe_string.rs @@ -92,6 +92,13 @@ impl Queryable for SafeString { } } +impl Queryable for SafeString { + type Row = String; + fn build(value: Self::Row) -> Self { + SafeString::new(&value) + } +} + impl ToSql for SafeString where DB: diesel::backend::Backend, diff --git a/plume-models/src/users.rs b/plume-models/src/users.rs index c26421bb..e8fa6729 100644 --- a/plume-models/src/users.rs +++ b/plume-models/src/users.rs @@ -6,7 +6,7 @@ use activitypub::{ }; use bcrypt; use chrono::{Utc, NaiveDateTime}; -use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, BelongingToDsl, dsl::any}; +use diesel::{self, QueryDsl, RunQueryDsl, ExpressionMethods, BelongingToDsl}; use openssl::{ hash::MessageDigest, pkey::{PKey, Private}, @@ -101,8 +101,8 @@ impl User { find_by!(users, find_by_ap_url, ap_url as String); pub fn one_by_instance(conn: &Connection) -> Vec { - users::table.distinct_on(users::instance_id) - .get_results::(conn) + users::table.filter(users::instance_id.eq_any(users::table.select(users::instance_id).distinct())) + .load::(conn) .expect("Error in User::on_by_instance") } @@ -117,7 +117,7 @@ impl User { pub fn grant_admin_rights(&self, conn: &Connection) { diesel::update(self) .set(users::is_admin.eq(true)) - .load::(conn) + .execute(conn) .expect("Couldn't grant admin rights"); } @@ -127,9 +127,9 @@ impl User { users::display_name.eq(name), users::email.eq(email), users::summary.eq(summary), - )).load::(conn) - .expect("Couldn't update user") - .into_iter().nth(0).unwrap() + )).execute(conn) + .expect("Couldn't update user"); + User::get(conn, self.id).unwrap() } pub fn count_local(conn: &Connection) -> usize { @@ -279,31 +279,31 @@ impl User { if self.outbox_url.len() == 0 { diesel::update(self) .set(users::outbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "outbox"))) - .get_result::(conn).expect("Couldn't update outbox URL"); + .execute(conn).expect("Couldn't update outbox URL"); } if self.inbox_url.len() == 0 { diesel::update(self) .set(users::inbox_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "inbox"))) - .get_result::(conn).expect("Couldn't update inbox URL"); + .execute(conn).expect("Couldn't update inbox URL"); } if self.ap_url.len() == 0 { diesel::update(self) .set(users::ap_url.eq(instance.compute_box(USER_PREFIX, self.username.clone(), ""))) - .get_result::(conn).expect("Couldn't update AP URL"); + .execute(conn).expect("Couldn't update AP URL"); } if self.shared_inbox_url.is_none() { diesel::update(self) .set(users::shared_inbox_url.eq(ap_url(format!("{}/inbox", Instance::get_local(conn).unwrap().public_domain)))) - .get_result::(conn).expect("Couldn't update shared inbox URL"); + .execute(conn).expect("Couldn't update shared inbox URL"); } if self.followers_endpoint.len() == 0 { diesel::update(self) .set(users::followers_endpoint.eq(instance.compute_box(USER_PREFIX, self.username.clone(), "followers"))) - .get_result::(conn).expect("Couldn't update followers endpoint"); + .execute(conn).expect("Couldn't update followers endpoint"); } } @@ -375,7 +375,7 @@ impl User { let posts_by_self = PostAuthor::belonging_to(self).select(post_authors::post_id); let posts = posts::table .filter(posts::published.eq(true)) - .filter(posts::id.eq(any(posts_by_self))) + .filter(posts::id.eq_any(posts_by_self)) .load::(conn).unwrap(); posts.into_iter().map(|p| { serde_json::to_value(p.create_activity(conn)).unwrap() @@ -393,22 +393,22 @@ impl User { pub fn get_followers(&self, conn: &Connection) -> Vec { use schema::follows; let follows = Follow::belonging_to(self).select(follows::follower_id); - users::table.filter(users::id.eq(any(follows))).load::(conn).unwrap() + users::table.filter(users::id.eq_any(follows)).load::(conn).unwrap() } pub fn get_followers_page(&self, conn: &Connection, (min, max): (i32, i32)) -> Vec { use schema::follows; let follows = Follow::belonging_to(self).select(follows::follower_id); - users::table.filter(users::id.eq(any(follows))) + users::table.filter(users::id.eq_any(follows)) .offset(min.into()) .limit((max - min).into()) .load::(conn).unwrap() } pub fn get_following(&self, conn: &Connection) -> Vec { - use schema::follows; - let follows = follows::table.filter(follows::follower_id.eq(self.id)).select(follows::following_id); - users::table.filter(users::id.eq(any(follows))).load::(conn).unwrap() + use schema::follows::dsl::*; + let f = follows.filter(follower_id.eq(self.id)).select(following_id); + users::table.filter(users::id.eq_any(f)).load::(conn).unwrap() } pub fn is_followed_by(&self, conn: &Connection, other_id: i32) -> bool { diff --git a/src/inbox.rs b/src/inbox.rs index 19e4efe3..d70fed5d 100644 --- a/src/inbox.rs +++ b/src/inbox.rs @@ -1,10 +1,10 @@ use activitypub::{activity::{Announce, Create, Delete, Like, Undo, Update}, object::Tombstone}; -use diesel::PgConnection; use failure::Error; use serde_json; use plume_common::activity_pub::{Id, inbox::{Deletable, FromActivity, InboxError}}; use plume_models::{ + Connection, comments::Comment, follows::Follow, instance::Instance, @@ -15,7 +15,7 @@ use plume_models::{ }; pub trait Inbox { - fn received(&self, conn: &PgConnection, act: serde_json::Value) -> Result<(), Error> { + fn received(&self, conn: &Connection, act: serde_json::Value) -> Result<(), Error> { let actor_id = Id::new(act["actor"].as_str().unwrap_or_else(|| act["actor"]["id"].as_str().expect("No actor ID for incoming activity"))); match act["type"].as_str() { Some(t) => { diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 25abb2a6..dfd51e22 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -1,5 +1,4 @@ use atom_syndication::{ContentBuilder, Entry, EntryBuilder, LinkBuilder, Person, PersonBuilder}; -use diesel::PgConnection; use rocket::{ http::uri::{FromUriParam, UriDisplay}, response::NamedFile @@ -9,7 +8,7 @@ use std::{ path::{Path, PathBuf} }; -use plume_models::posts::Post; +use plume_models::{Connection, posts::Post}; macro_rules! may_fail { ($account:expr, $expr:expr, $template:expr, $msg:expr, | $res:ident | $block:block) => { @@ -79,7 +78,7 @@ impl Page { } } -pub fn post_to_atom(post: Post, conn: &PgConnection) -> Entry { +pub fn post_to_atom(post: Post, conn: &Connection) -> Entry { EntryBuilder::default() .title(post.title.clone()) .content(ContentBuilder::default() diff --git a/src/setup.rs b/src/setup.rs index 83c86c5c..16736d1e 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1,5 +1,5 @@ use colored::Colorize; -use diesel::{pg::PgConnection, r2d2::{ConnectionManager, Pool}}; +use diesel::r2d2::{ConnectionManager, Pool}; use dotenv::dotenv; use std::fs::{self, File}; use std::io; @@ -9,21 +9,22 @@ use rpassword; use plume_models::safe_string::SafeString; use plume_models::{ + Connection, DB_URL, - db_conn::{DbConn, PgPool}, + db_conn::{DbConn, DbPool}, instance::*, users::* }; /// Initializes a database pool. -fn init_pool() -> Option { +fn init_pool() -> Option { dotenv().ok(); - let manager = ConnectionManager::::new(DB_URL.as_str()); + let manager = ConnectionManager::::new(DB_URL.as_str()); Pool::new(manager).ok() } -pub fn check() -> PgPool { +pub fn check() -> DbPool { if let Some(pool) = init_pool() { match pool.get() { Ok(conn) => {