generated from t/malachite
add: model
This commit is contained in:
parent
f70b92c558
commit
d7ee379a9a
13 changed files with 394 additions and 219 deletions
101
src/database/chats.rs
Normal file
101
src/database/chats.rs
Normal file
|
@ -0,0 +1,101 @@
|
|||
use super::DataManager;
|
||||
use crate::model::{Chat, ChatStyle};
|
||||
use oiseau::{PostgresRow, cache::Cache, execute, get, params};
|
||||
use tetratto_core::{
|
||||
auto_method,
|
||||
model::{Error, Result},
|
||||
};
|
||||
|
||||
impl DataManager {
|
||||
/// Get a [`Chat`] from an SQL row.
|
||||
pub(crate) fn get_chat_from_row(x: &PostgresRow) -> Chat {
|
||||
Chat {
|
||||
id: get!(x->0(i64)) as usize,
|
||||
created: get!(x->1(i64)) as usize,
|
||||
style: serde_json::from_str(&get!(x->2(String))).unwrap(),
|
||||
members: serde_json::from_str(&get!(x->3(String))).unwrap(),
|
||||
last_message_created: get!(x->4(i64)) as usize,
|
||||
last_message_read_by: serde_json::from_str(&get!(x->5(String))).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
auto_method!(get_chat_by_id(usize as i64)@get_chat_from_row -> "SELECT * FROM t_chats WHERE id = $1" --name="chat" --returns=Chat --cache-key-tmpl="twny.chat:{}");
|
||||
|
||||
/// Create a new chat in the database.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `data` - a mock [`Chat`] object to insert
|
||||
pub async fn create_chat(&self, data: Chat) -> Result<Chat> {
|
||||
// check values
|
||||
if let ChatStyle::Group(ref info) = data.style {
|
||||
if info.name.trim().len() < 2 {
|
||||
return Err(Error::DataTooShort("name".to_string()));
|
||||
} else if info.name.len() > 128 {
|
||||
return Err(Error::DataTooLong("name".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
let conn = match self.0.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
let res = execute!(
|
||||
&conn,
|
||||
"INSERT INTO t_chats VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
params![
|
||||
&(data.id as i64),
|
||||
&(data.created as i64),
|
||||
&serde_json::to_string(&data.style).unwrap(),
|
||||
&serde_json::to_string(&data.members).unwrap(),
|
||||
&(data.last_message_created as i64),
|
||||
&serde_json::to_string(&data.last_message_read_by).unwrap()
|
||||
]
|
||||
);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Delete an existing chat.
|
||||
pub async fn delete_chat(&self, id: usize) -> Result<()> {
|
||||
let conn = match self.0.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
// delete chat
|
||||
let res = execute!(
|
||||
&conn,
|
||||
"DELETE FROM t_chats WHERE id = $1",
|
||||
params![&(id as i64)]
|
||||
);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
// delete messages
|
||||
let res = execute!(
|
||||
&conn,
|
||||
"DELETE FROM t_messages WHERE chat = $1",
|
||||
params![&(id as i64)]
|
||||
);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
// ...
|
||||
Ok(())
|
||||
}
|
||||
|
||||
auto_method!(update_chat_style(ChatStyle) -> "UPDATE t_chats SET style = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.chat:{}");
|
||||
auto_method!(update_chat_members(Vec<usize>) -> "UPDATE t_chats SET members = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.chat:{}");
|
||||
auto_method!(update_chat_last_message_read_by(Vec<usize>) -> "UPDATE t_chats SET last_message_read_by = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.chat:{}");
|
||||
auto_method!(update_chat_last_message_created(i64) -> "UPDATE t_chats SET last_message_created = $1 WHERE id = $2" --cache-key-tmpl="twny.chat:{}");
|
||||
}
|
99
src/database/messages.rs
Normal file
99
src/database/messages.rs
Normal file
|
@ -0,0 +1,99 @@
|
|||
use super::DataManager;
|
||||
use crate::model::Message;
|
||||
use oiseau::{PostgresRow, cache::Cache, execute, get, params};
|
||||
use tetratto_core::{
|
||||
auto_method,
|
||||
model::{Error, Result, auth::User},
|
||||
};
|
||||
|
||||
impl DataManager {
|
||||
/// Get a [`Message`] from an SQL row.
|
||||
pub(crate) fn get_message_from_row(x: &PostgresRow) -> Message {
|
||||
Message {
|
||||
id: get!(x->0(i64)) as usize,
|
||||
created: get!(x->1(i64)) as usize,
|
||||
owner: get!(x->2(i64)) as usize,
|
||||
chat: get!(x->3(i64)) as usize,
|
||||
content: get!(x->4(String)),
|
||||
uploads: serde_json::from_str(&get!(x->5(String))).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
auto_method!(get_message_by_id(usize as i64)@get_message_from_row -> "SELECT * FROM t_messages WHERE id = $1" --name="message" --returns=Message --cache-key-tmpl="twny.message:{}");
|
||||
|
||||
/// Create a new message in the database.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `data` - a mock [`Message`] object to insert
|
||||
pub async fn create_message(&self, data: Message) -> Result<Message> {
|
||||
// check values
|
||||
if data.content.trim().len() < 2 {
|
||||
return Err(Error::DataTooShort("content".to_string()));
|
||||
} else if data.content.len() > 2048 {
|
||||
return Err(Error::DataTooLong("content".to_string()));
|
||||
}
|
||||
|
||||
// ...
|
||||
let conn = match self.0.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
let res = execute!(
|
||||
&conn,
|
||||
"INSERT INTO t_messages VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
params![
|
||||
&(data.id as i64),
|
||||
&(data.created as i64),
|
||||
&(data.owner as i64),
|
||||
&(data.chat as i64),
|
||||
&data.content,
|
||||
&serde_json::to_string(&data.uploads).unwrap(),
|
||||
]
|
||||
);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Delete an existing message.
|
||||
pub async fn delete_message(&self, id: usize, user: &User) -> Result<()> {
|
||||
let message = self.get_message_by_id(id).await?;
|
||||
|
||||
if message.owner != user.id {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
|
||||
// ...
|
||||
let conn = match self.0.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
// delete message
|
||||
let res = execute!(
|
||||
&conn,
|
||||
"DELETE FROM t_messages WHERE id = $1",
|
||||
params![&(id as i64)]
|
||||
);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
// delete uploads
|
||||
for upload in message.uploads {
|
||||
if let Err(e) = self.1.delete_upload(upload).await {
|
||||
return Err(Error::MiscError(e.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
Ok(())
|
||||
}
|
||||
|
||||
auto_method!(update_message_content(&str) -> "UPDATE t_messages SET content = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.message:{}");
|
||||
}
|
|
@ -1,18 +1,28 @@
|
|||
mod chats;
|
||||
mod messages;
|
||||
mod sql;
|
||||
|
||||
use crate::config::Config;
|
||||
use buckets_core::{Config as BucketsConfig, DataManager as BucketsManager};
|
||||
use oiseau::{execute, postgres::DataManager as OiseauManager, postgres::Result as PgResult};
|
||||
use std::collections::HashMap;
|
||||
use tetratto_core::model::{Error, Result};
|
||||
|
||||
pub const NAME_REGEX: &str = r"[^\w_\-\.,!]+";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DataManager(pub OiseauManager<Config>);
|
||||
pub struct DataManager(pub OiseauManager<Config>, pub BucketsManager);
|
||||
|
||||
impl DataManager {
|
||||
/// Create a new [`DataManager`].
|
||||
pub async fn new(config: Config) -> PgResult<Self> {
|
||||
Ok(Self(OiseauManager::new(config).await?))
|
||||
let buckets_manager = BucketsManager::new(BucketsConfig {
|
||||
directory: config.uploads_dir.clone(),
|
||||
bucket_defaults: HashMap::new(),
|
||||
database: config.database.clone(),
|
||||
})
|
||||
.await
|
||||
.expect("failed to create buckets manager");
|
||||
|
||||
Ok(Self(OiseauManager::new(config).await?, buckets_manager))
|
||||
}
|
||||
|
||||
/// Initialize tables.
|
||||
|
@ -22,7 +32,8 @@ impl DataManager {
|
|||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
// execute!(&conn, sql::CREATE_TABLE_ENTRIES).unwrap();
|
||||
execute!(&conn, sql::CREATE_TABLE_CHATS).unwrap();
|
||||
execute!(&conn, sql::CREATE_TABLE_MESSAGES).unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
8
src/database/sql/create_chats.sql
Normal file
8
src/database/sql/create_chats.sql
Normal file
|
@ -0,0 +1,8 @@
|
|||
CREATE TABLE IF NOT EXISTS t_chats (
|
||||
id BIGINT NOT NULL,
|
||||
created BIGINT NOT NULL,
|
||||
style TEXT NOT NULL,
|
||||
members TEXT NOT NULL,
|
||||
last_message_created BIGINT NOT NULL,
|
||||
last_message_read_by TEXT NOT NULL
|
||||
);
|
8
src/database/sql/create_messages.sql
Normal file
8
src/database/sql/create_messages.sql
Normal file
|
@ -0,0 +1,8 @@
|
|||
CREATE TABLE IF NOT EXISTS t_messages (
|
||||
id BIGINT NOT NULL,
|
||||
created BIGINT NOT NULL,
|
||||
owner BIGINT NOT NULL,
|
||||
chats BIGINT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
uploads TEXT NOT NULL
|
||||
);
|
|
@ -1 +1,2 @@
|
|||
// pub const CREATE_TABLE_ENTRIES: &str = include_str!("./create_entries.sql");
|
||||
pub const CREATE_TABLE_CHATS: &str = include_str!("./create_chats.sql");
|
||||
pub const CREATE_TABLE_MESSAGES: &str = include_str!("./create_messages.sql");
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue