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<()> {
database::query("CREATE TABLE messages(msg text, handle text)".to_string())
.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
}
pub fn add_post(msg: String, handle: String) -> AppResult<()> {
2019-08-14 23:22:15 +03:00
database::query(format!(
r#"INSERT INTO messages VALUES("{}","{}")"#,
msg, handle
))
.map_err(|e| {
err_msg(&format!(
"Error inserting post {} by {}: {}",
msg, handle, e
))
})
.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(
json_object('msg', msg, 'handle', handle)
) AS json_result FROM (SELECT * FROM messages)"
.to_string(),
)
.map_err(|e| err_msg(&format!("Error retrieving posts: {}", e)))
}
2019-08-15 13:00:52 +03:00
pub fn get_posts_by_handle(handle: String) -> AppResult<String> {
database::query(format!(
"SELECT json_group_array(
json_object('msg', msg, 'handle', handle)
) AS json_result FROM (SELECT * FROM messages where handle = '{}')",
handle
))
.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
}