58 lines
1.7 KiB
Rust
Raw Normal View History

2019-08-14 23:22:15 +03:00
use std::str::FromStr;
2019-08-14 22:15:38 +03:00
use crate::api::AppResult;
2019-08-14 23:22:15 +03:00
use crate::database;
2019-08-14 22:15:38 +03:00
use crate::errors::err_msg;
pub fn create_scheme() -> AppResult<()> {
2019-08-15 19:10:13 +03:00
database::query("CREATE TABLE messages(msg text, username text)".to_string())
2019-08-14 22:15:38 +03:00
.map_err(|e| err_msg(&format!("Error creating table messages: {}", e)))
2019-08-14 23:22:15 +03:00
.map(|_| ())
2019-08-14 22:15:38 +03:00
}
2019-08-15 19:10:13 +03:00
pub fn add_post(msg: String, username: String) -> AppResult<()> {
2019-08-14 23:22:15 +03:00
database::query(format!(
r#"INSERT INTO messages VALUES("{}","{}")"#,
2019-08-15 19:10:13 +03:00
msg, username
2019-08-14 23:22:15 +03:00
))
.map_err(|e| {
err_msg(&format!(
"Error inserting post {} by {}: {}",
2019-08-15 19:10:13 +03:00
msg, username, e
2019-08-14 23:22:15 +03:00
))
})
.map(|_| ())
2019-08-14 22:15:38 +03:00
}
2019-08-15 13:00:52 +03:00
pub fn get_all_posts() -> AppResult<String> {
2019-08-14 22:15:38 +03:00
database::query(
"SELECT json_group_array(
2019-08-15 19:10:13 +03:00
json_object('msg', msg, 'username', username)
2019-08-14 22:15:38 +03:00
) AS json_result FROM (SELECT * FROM messages)"
.to_string(),
)
.map_err(|e| err_msg(&format!("Error retrieving posts: {}", e)))
}
2019-08-15 19:10:13 +03:00
pub fn get_posts_by_handle(username: String) -> AppResult<String> {
2019-08-15 13:00:52 +03:00
database::query(format!(
"SELECT json_group_array(
2019-08-15 19:10:13 +03:00
json_object('msg', msg, 'username', username)
) AS json_result FROM (SELECT * FROM messages where username = '{}')",
username
2019-08-15 13:00:52 +03:00
))
.map_err(|e| err_msg(&format!("Error retrieving posts: {}", e)))
}
2019-08-14 22:15:38 +03:00
pub fn get_posts_count() -> AppResult<i32> {
2019-08-14 23:22:15 +03:00
let result = database::query("SELECT COUNT(*) from messages".to_string())
.map_err(|e| err_msg(&format!("Error retrieving posts count: {}", e)))?;
i32::from_str(result.as_str()).map_err(|e| {
err_msg(&format!(
"Can't parse {} to i32 in get_posts_count: {}",
result, e
))
})
2019-08-14 22:15:38 +03:00
}