Adding functions to db::message module
This commit is contained in:
@@ -23,3 +23,69 @@ pub async fn insert(
|
|||||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn get(
|
||||||
|
pool: &sqlx::PgPool,
|
||||||
|
id: &uuid::Uuid,
|
||||||
|
) -> Result<textsender_models::message::Message, sqlx::Error> {
|
||||||
|
match sqlx::query(
|
||||||
|
r#"
|
||||||
|
SELECT id, content, user_id FROM "messages"
|
||||||
|
WHERE
|
||||||
|
id = $1;
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(row) => {
|
||||||
|
let id: uuid::Uuid = row.try_get("id")?;
|
||||||
|
|
||||||
|
let content: String = row.try_get("content")?;
|
||||||
|
let user_id: uuid::Uuid = row.try_get("user_id")?;
|
||||||
|
Ok(textsender_models::message::Message {
|
||||||
|
id: Some(id),
|
||||||
|
content,
|
||||||
|
user_id: Some(user_id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_with_user_id(
|
||||||
|
pool: &sqlx::PgPool,
|
||||||
|
user_id: &uuid::Uuid,
|
||||||
|
) -> Result<Vec<textsender_models::message::Message>, sqlx::Error> {
|
||||||
|
match sqlx::query(
|
||||||
|
r#"
|
||||||
|
SELECT id, content, user_id FROM "messages"
|
||||||
|
WHERE
|
||||||
|
user_id = $1;
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(rows) => {
|
||||||
|
let mut messages: Vec<textsender_models::message::Message> = Vec::new();
|
||||||
|
for row in rows {
|
||||||
|
let id: uuid::Uuid = row.try_get("id")?;
|
||||||
|
let content: String = row.try_get("content")?;
|
||||||
|
let user_id: uuid::Uuid = row.try_get("user_id")?;
|
||||||
|
|
||||||
|
let message = textsender_models::message::Message {
|
||||||
|
id: Some(id),
|
||||||
|
content,
|
||||||
|
user_id: Some(user_id),
|
||||||
|
};
|
||||||
|
messages.push(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(messages)
|
||||||
|
}
|
||||||
|
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user