Skip to content
This repository has been archived by the owner on Feb 4, 2020. It is now read-only.

Implement admin feature for DB manipulation #23

Merged
merged 4 commits into from Oct 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
137 changes: 137 additions & 0 deletions burning-pro-server/src/db/admin.rs
@@ -0,0 +1,137 @@
//! DB administration mesasages.

use std::iter;
use std::marker::PhantomData;

use actix::prelude::*;
use diesel;
use diesel::prelude::*;
use diesel::result::DatabaseErrorKind;

use db::{DbExecutor, Error};
use models;

/// A message type to get table rows.
///
/// This may have query parameters to limit or filter results (while it does not
/// for now).
#[derive(Debug, Clone)]
pub struct GetTableRows<T>(PhantomData<T>);

impl<T: 'static> Message for GetTableRows<T> {
type Result = Result<Vec<T>, Error>;
}

/// A message type to upsert rows to DB table.
#[derive(Debug, Clone)]
pub struct UpsertTableRows<T> {
rows: Vec<T>,
}

impl<T> UpsertTableRows<T> {
/// Creates a new `UpsertTableRows`.
pub fn new() -> Self {
Self::default()
}

/// Creates a new `UpsertTableRows` from the given row.
pub fn from_row(row: T) -> Self {
Self { rows: vec![row] }
}

/// Creates a new `UpsertTableRows` from the given rows.
pub fn from_rows(rows: Vec<T>) -> Self {
Self { rows }
}
}

impl<T> Default for UpsertTableRows<T> {
fn default() -> Self {
Self {
rows: Default::default(),
}
}
}

impl<T> iter::Extend<T> for UpsertTableRows<T> {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
self.rows.extend(iter)
}
}

impl<T: 'static> Message for UpsertTableRows<T> {
type Result = Result<usize, Error>;
}

macro_rules! impl_handler_for_model {
($model:ty) => {
impl Handler<GetTableRows<$model>> for DbExecutor {
type Result = <GetTableRows<$model> as Message>::Result;

fn handle(
&mut self,
_msg: GetTableRows<$model>,
_ctx: &mut Self::Context,
) -> Self::Result {
use diesel::associations::HasTable;

let conn = &self.pool().get()?;
Ok(<$model>::table().load::<$model>(conn)?)
}
}

impl Handler<UpsertTableRows<$model>> for DbExecutor {
type Result = <UpsertTableRows<$model> as Message>::Result;

fn handle(
&mut self,
msg: UpsertTableRows<$model>,
_ctx: &mut Self::Context,
) -> Self::Result {
use diesel::associations::HasTable;

let conn = &self.pool().get()?;

// NOTE: SQLite backend does not support batch insert.
// See <https://github.com/diesel-rs/diesel/issues/1822>.
let result = msg
.rows
.iter()
.map(|row| {
// NOTE: SQLite backend does not support upsert.
// See <https://github.com/diesel-rs/diesel/issues/1854>.

// First, try to insert the row.
let insert_result = diesel::insert_into(<$model>::table())
.values(row)
.execute(conn);
match insert_result {
Ok(_) => return Ok(()),
Err(diesel::result::Error::DatabaseError(
DatabaseErrorKind::UniqueViolation,
_,
)) => {}
Err(err) => return Err(err),
}

// If insert fails, a row with the same id already exists.
// Then try to replace the row.
diesel::replace_into(<$model>::table())
.values(row)
.execute(conn)
.map(|_| ())
}).collect::<Result<Vec<_>, _>>()?;
Ok(result.len())
}
}
};
}

impl_handler_for_model!(models::GoodPhraseTag);
impl_handler_for_model!(models::GoodPhrase);
impl_handler_for_model!(models::GoodPhraseAndTag);
impl_handler_for_model!(models::PersonUrl);
impl_handler_for_model!(models::Person);
1 change: 1 addition & 0 deletions burning-pro-server/src/db/mod.rs
Expand Up @@ -9,6 +9,7 @@ use r2d2;

pub use self::get_good_phrases::GetGoodPhrases;

pub mod admin;
mod get_good_phrases;

/// DB operation error.
Expand Down
44 changes: 39 additions & 5 deletions burning-pro-server/src/models/mod.rs
Expand Up @@ -4,7 +4,9 @@ use chrono::NaiveDateTime;
use schema::*;

/// GoodPhrase tag.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Queryable)]
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Queryable, Insertable,
)]
#[primary_key(good_phrase_tag_id)]
pub struct GoodPhraseTag {
/// Row ID.
Expand All @@ -21,7 +23,17 @@ pub struct GoodPhraseTag {

/// GoodPhrase.
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Associations, Identifiable, Queryable,
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Hash,
Serialize,
Associations,
Identifiable,
Queryable,
Insertable,
)]
#[belongs_to(Person)]
#[primary_key(good_phrase_id)]
Expand All @@ -48,7 +60,17 @@ pub struct GoodPhrase {

/// GoodPhrase and tag.
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Associations, Identifiable, Queryable,
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Hash,
Serialize,
Associations,
Identifiable,
Queryable,
Insertable,
)]
#[belongs_to(GoodPhrase)]
#[belongs_to(GoodPhraseTag)]
Expand All @@ -69,7 +91,17 @@ pub struct GoodPhraseAndTag {

/// Person and URL.
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Associations, Identifiable, Queryable,
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Hash,
Serialize,
Associations,
Identifiable,
Queryable,
Insertable,
)]
#[belongs_to(Person)]
#[table_name = "person_urls"]
Expand All @@ -88,7 +120,9 @@ pub struct PersonUrl {
}

/// Person.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Queryable)]
#[derive(
Debug, Clone, PartialEq, Eq, PartialOrd, Hash, Serialize, Identifiable, Queryable, Insertable,
)]
#[primary_key(person_id)]
pub struct Person {
/// Row ID.
Expand Down